Peter T.
Peter T.

Reputation: 3315

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

I have a Vue component that has a property defined using a decorator:

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'."
  }
}

I can avoid the type error by converting this to any:

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

But this is rather a work around than a solution.

I guess compiler isn't aware of the properties defined by the @Component decorator?

Any ideas?

Upvotes: 1

Views: 938

Answers (2)

coffidev
coffidev

Reputation: 999

I recommend you to use this library: https://github.com/kaorun343/vue-property-decorator

With this you can declare your prop inside your component class.

For example:

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

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

Upvotes: 3

Ruan Mendes
Ruan Mendes

Reputation: 92274

The TypeScript example states that you must document them yourself in the component.

From that page

  // 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'."
  }
}

Upvotes: 1

Related Questions