gpt4 book ai didi

typescript - 使用 Typescript 在 Vue 数据对象中设置数据类型

转载 作者:搜寻专家 更新时间:2023-10-30 20:33:23 25 4
gpt4 key购买 nike

我目前在 webpack 项目中使用 Vue.js 和 Typescript。

Recommended Configuration 中所示在我的 tsconfig.json 我有:

"严格": 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'.

因为我相信 玩家:[]never[] 类型。

我的问题是:如何推断类型 Vue 数据对象的属性??

最佳答案

要添加到 Joshua 的答案中,您可能需要声明内联玩家的类型,这样您的代码就不会随着数据变大而变得过于冗长。

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

另一种选择:

data() {
return {
players: new Array<Player>()
};
},

关于typescript - 使用 Typescript 在 Vue 数据对象中设置数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47810218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com