Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set data Type in Vue data object with Typescript

I'm currently using Vue.js with Typescript in a webpack project.

As indicated in the Recommended Configuration in my tsconfig.json I have:

"strict": true,

Inside one of my component i have:

declare interface Player {     cod: string,     param: string   }  export default Vue.extend({     name: 'basecomponent',     data() {       return {         players: []       };     },     created()        let self = this       axios.get('fetch-data')         .then((response) => {           let res: Players[] = response.data;           for(let i = 0; i < res.length; i++){               self.players.push(res[i]);           }         })         .catch((error: string) => {           console.log(error);        });     },  }); 

but when I try to compile i get:

 error TS2345: Argument of type 'Player' is not assignable to parameter of type 'never'. 

Cause I believe players: [] has never[] type.

My question is: how can I infer type Vue data object properties??

like image 583
Plastic Avatar asked Dec 14 '17 09:12

Plastic


1 Answers

To add to Joshua's answer, you may want to declare the type of players inline so your code doesn't get too verbose as your data gets larger.

data() {   return {     players: [] as Player[]   }; }, 

another option:

data() {   return {     players: new Array<Player>()   }; }, 
like image 128
Michael Wilson Avatar answered Sep 21 '22 12:09

Michael Wilson