5

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.

2

2 Answers 2

5

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[]
    }
  }
})
Sign up to request clarification or add additional context in comments.

3 Comments

You should consider explaining your answer in more depth. It was labeled as "low quality" because it is mostly code.
I figured it was too trivial to explain in detail when compared to OP's code. Updated.
This is exactly what I was looking for in this kind of component, but it turns out I should use different syntax, thank you very much! +1
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.