Xavier Poinas
Xavier Poinas

Reputation: 19733

Type checking a simple Vue.js app with TypeScript

Vue.js comes with official TypeScript type definitions that are installed along the library with NPM.

I am trying to use them to type check a simple app. All of the samples I've found demonstrate the use of TypeScript in components but I couldn't find a way to type check a simple app like:

import * as Vue from 'vue';

interface Item {
    name: string;
}

var app = new Vue({
  el: '#app',
  data: {
    items: <Item[]> []
  },
  methods: {
    addItem: function () {
      this.items.push({ name: 'Item' });
    }
  }
});

I guess that the main challenge is that all the data, methods, computed properties, etc., should all be available on this. However in this case, this is of type Vue and does not contain an items property.

Is there a way to pull this off?

Upvotes: 1

Views: 1632

Answers (1)

Byrd
Byrd

Reputation: 907

Something like this might help, I am not too familiar with VueJS but try this

import * as Vue from 'vue';

interface Item {
   name: string;
}

interface App extends Vue {
   items: Item[];
}

export default {
  el: '#app',
  data: {
    items: <Item[]> []
  },
  methods: {
    addItem: function () {
      this.items.push({ name: 'Item' });
    }
  }
} as ComponentOptions<App>

The alternative is using a peer dependency

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
  el: '#app' //... rest of your options
})
export default class Item extends Vue {
  // Initial data can be declared as instance properties
  items: <Item[]> []
  // Component methods can be declared as instance methods
  addItem (): void {
    this.items.push({name: 'Item' });
  }
}

Upvotes: 3

Related Questions