网站搜索

如何在 TypeScript 中从构造函数动态声明类的实例属性?


我尝试用 TypeScript 编写一个简单的 VUE,但第一步就失败了。我找到了很多答案,却没有找到能解决我问题的方案。

我想动态地声明类的一些属性,这些属性通过构造函数获取,但我不知道如何编写这样的声明。

环境

TypeScript 3.4.5

interface IOptions {
  data: () => Record<string, any>
}

class Vue {
  private $options: IOptions = {
    data: () => ({})
  }

  constructor(options: IOptions) {
    this.$options = options
    const proxy = this.initProxy()
    return proxy
  }

  initProxy() {
    const data = this.$options.data ? this.$options.data() : {}

    return new Proxy(this, {
      set(_, key: string, value) {
        data[key] = value
        return true
      },
      get(_, key: string) {
        return data[key]
      }
    })
  }
}

const vm = new Vue({
  data() {
    return {
      a: 1
    }
  }
})

vm.a = 2
// ^ Property 'a' does not exist on type 'Vue'.

console.log(vm.a) // => 2
//             ^ Property 'a' does not exist on type 'Vue'.

这是网址 https://stackblitz.com/edit/typescript-kh4zmn 的在线预览

打开它,你可以看到控制台输出了预期的结果,但编辑器显示 TypeScript 错误,提示 Property 'a' does not exist on type 'Vue'.。

我期望vm具有正确的类型,这样我就可以无错误地访问构造函数中声明的属性。

答案#1

问题的第一部分是正确获取 initProxy 的返回类型。由于你将 data 返回的所有属性都添加到了代理中,返回类型应包含它们。为了实现这一点,我们需要给 Vue 类添加一个类型参数(T)。这个类型参数将捕获 data 返回类型的实际类型。有了这个类型参数,我们就可以让 TypeScript 知道 initProxy 实际上返回 T & Vue<T>,也就是说,它返回一个既是 T 又是原始类的对象。

interface IOptions<T> {
    data: () => T
}

class Vue<T = {}> {
    private $options: IOptions<T> = {
        data: () => ({})
    } as IOptions<T>

    constructor(options: IOptions<T>) {
        this.$options = options
        const proxy = this.initProxy()
        return proxy
    }
    initProxy(): T & Vue<T> {
        const data = this.$options.data ? this.$options.data() : {}

        return new Proxy(this as unknown as T & Vue<T>, {
            set(_, key: string, value) {
                data[key] = value
                return true
            },
            get(_, key: string) {
                return data[key]
            }
        })
    }
}

const vm = new Vue({
    data() {
        return {
            a: 1
        }
    }
})
vm.initProxy().a // ok now

问题的第二部分是,虽然 TypeScript 允许你从构造函数中返回一个对象,但这不会以任何方式改变构造函数调用的返回类型(也无法为构造函数的返回类型添加注解)。这就是为什么尽管 vm.initProxy().a 可行,vm.a 仍然不可行的原因。

为绕过这个限制,我们有两个选择:

  1. 使用私有构造函数和类型正确的静态方法:

    class Vue<T = {}> {
        private $options: IOptions<T> = {
            data: () => ({})
        } as IOptions<T>
    
        private constructor(options: IOptions<T>) {
            this.$options = options
            const proxy = this.initProxy()
            return proxy
        }
        static create<T>(data: IOptions<T>):Vue<T> & T {
            return new Vue<T>(data) as unknown as Vue<T> & T 
        }
        initProxy(): T & Vue<T> {
            const data = this.$options.data ? this.$options.data() : {}
    
            return new Proxy(this as unknown as T & Vue<T>, {
                set(_, key: string, value) {
                    data[key] = value
                    return true
                },
                get(_, key: string) {
                    return data[key]
                }
            })
        }
    }
    
    
    const vm = Vue.create({
        data() {
            return {
                a: 1
            }
        }
    })
    vm.a = 2;
    
  2. 为课程使用单独的签名

    class _Vue<T = {}> {
        private $options: IOptions<T> = {
            data: () => ({})
        } as IOptions<T>
    
        private constructor(options: IOptions<T>) {
            this.$options = options
            const proxy = this.initProxy()
            return proxy
        }
        initProxy(): Vue<T> {
            const data = this.$options.data ? this.$options.data() : {}
    
            return new Proxy(this as unknown as Vue<T>, {
                set(_, key: string, value) {
                    data[key] = value
                    return true
                },
                get(_, key: string) {
                    return data[key]
                }
            })
        }
    }
    type Vue<T> = _Vue<T> & T
    const Vue: new<T>(data: IOptions<T>) => Vue<T> = _Vue as any
    
    const vm = new Vue({
        data() {
            return {
                a: 1
            }
        }
    })
    vm.a = 2;
    

答案#2

Typescript 不知道 Proxy 以及它可能接受的属性名称。例如,考虑以下 setter:

set(_, key: string, value: any) {
  if (!key.startsWith('foo')) {
    return false;
  }

  data[key] = value;
  return true;
}

TypeScript必须运行代码来确定这里哪些属性名称是合法的。

解决你问题的一个快速方法是在 Vue 类中添加一个类似 [key: string]: unknown; 的属性,这将告诉 TypeScript 只要键是 string 类型,就接受任何值,而不管它的类型。这将使你的示例能够编译。

不过,如果可能的话,你应该考虑适当地声明 Vue 类将使用的属性,以利用 TypeScript 的静态类型检查。