我目前在 webpack 项目中使用 Vue.js 和 Typescript。
如我的 tsconfig.json
中的 推荐配置 中所示,我有:
"strict": true,
在我的一个组件中,我有:
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);
});
},
});
但是当我尝试编译时,我得到:
error TS2345: Argument of type 'Player' is not assignable to parameter of type 'never'.
因为我相信 players: []
有 never[]
类型。
我的问题是:如何推断类型 Vue 数据对象属性?
原文由 Plastic 发布,翻译遵循 CC BY-SA 4.0 许可协议
要添加到 Joshua 的答案中,您可能需要内联声明播放器的类型,这样您的代码就不会因为数据变大而变得过于冗长。
另外的选择: