简体   繁体   中英

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.

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[]
    }
  }
})

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)
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM