p-sara
p-sara

Reputation: 339

Vue.js typescript interface not working

Does anyone know what's the syntaxt to create a type for data properties in vue.js (application is being written in typescript)? I'm looking for something like:

@Component({
  data() {
    return {
      sections: Array<SomeInterface> = []
    }
  }
})

But vue sees a type as a value and I'm confused how to approach it.

Upvotes: 5

Views: 4376

Answers (2)

SLaks
SLaks

Reputation: 887479

You should use class-style components using vue-class-component, which allow you to move these declarations to class properties and plays well with Typescript.

import Vue from 'vue'
import Component from 'vue-class-component'

// The @Component decorator indicates the class is a Vue component
@Component({
  // All component options are allowed in here
  template: '<button @click="onClick">Click!</button>'
})
export default class MyComponent extends Vue {
  // Initial data can be declared as instance properties
  message: string = 'Hello!'

  // Component methods can be declared as instance methods
  onClick (): void {
    window.alert(this.message)
  }
}

Upvotes: 1

Decade Moon
Decade Moon

Reputation: 34286

You can't use : as you normally would to precede the type because the syntax conflicts with JavaScript's key: value object literal syntax. You can just use type inference instead by forcing the empty array [] to the SomeInterface[] type:

@Component({
  data() {
    return {
      sections: [] as SomeInterface[]
    }
  }
})

Upvotes: 5

Related Questions