TommyD
TommyD

Reputation: 1043

Vue type script - data and custom types

I have a type called student.

export interface Student {
  name: string,
  age: number
}

I want to assign that type to data to a student.

data() {
const tommy: Student = {}
return {
  tommy,

}

However when I assign a string to that data in the mounted hook I get no warnings or issues.

  async mounted() {
    this.tommy= 'Tommy Smith'

How should I define custom data types in vue typescript.

Upvotes: 1

Views: 972

Answers (1)

Richard Leichner
Richard Leichner

Reputation: 11

You could either choose to use the Composition API where you can instantiate an Object with a certain class the way you did: const tommy: Student;

or if you want to continue using the Options API you could use type assertions like this:

data() {
    return {
      tommy: {name: '', age: 0} as Student
    }
}

problem furthermore: you assigned a string to tommy, instead you should assign the string to the name property:

  async mounted() {
    this.tommy.name = 'Tommy Smith'

Upvotes: 1

Related Questions