TypeScript 抱怨用 vue-属性-decorator 定义的现有 Vue 组件 属性

TypeScript complains about existing Vue component property defined with vue-property-decorator

我有一个 Vue 组件,它有一个 属性 使用装饰器定义:

import { Component, Vue } from "vue-property-decorator"
@Component({
             props: {
               myId: String,
             },
           })
class TestProp extends Vue {
  myFunction(obj: any) {
    return obj[this.myId] // here tslint complains: "Property 'myId' does not exist on type 'TestProp'."
  }
}

我可以通过将 this 转换为 any 来避免类型错误:

  myFunction(obj: any) {
    return obj[(this as any).myId]
  }

但这与其说是一种解决方案,不如说是一种变通方法。

我想编译器不知道 @Component 装饰器定义的属性?

有什么想法吗?

TypeScript example 声明您必须自己在组件中记录它们。

来自那个页面

  // additional declaration is needed
  // when you declare some properties in `Component` decorator
import { Component, Vue } from "vue-property-decorator"
@Component({
  props: {
    myId: String,
  },
})
class TestProp extends Vue {

  myId: string;

  myFunction(obj: any) {
    return obj[this.myId] // here tslint complains: "Property 'myId' does not exist on type 'TestProp'."
  }
}

我推荐你使用这个库:https://github.com/kaorun343/vue-property-decorator

有了这个,你可以在你的组件中声明你的道具 class。

例如:

import { Vue, Component, Prop } from 'vue-property-decorator'

@Component
class TestProp extends Vue {
  @Prop(String) myId: string!
}