【发布时间】:2019-04-24 09:08:22
【问题描述】:
我尝试使用 typescript 编写一个简单的 VUE,但第一步失败了。我找到了很多答案,但没有找到可以解决我的问题的解决方案。
我想动态声明类的一些属性,它们是通过构造函数得到的,但我不知道如何编写这样的声明。
环境
打字稿 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的在线预览
打开它,你可以看到控制台输出了预期的输出,但是编辑器给出了一个打字稿错误Property 'a' does not exist on type 'Vue'.。
我希望vm 具有正确的类型,以便我可以访问构造函数中声明的属性而不会出错。
【问题讨论】:
标签: typescript class constructor