1

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?

1 Answer 1

3

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

2 Comments

Thanks! I had to adjust the 1st example to make it work (see my edit). However, the 2nd one didn't work for me. I don't have a 'vue-class-component' module to import from, and when I try import Component from 'vue', the compiler complains that Component is not callable.
Yeah for the second example you'd need to npm install it. The first example has some shortcomings.

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.