使用 Typescript 设置 Vue 数据对象中的数据类型

2024-01-06

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

如中所示推荐配置 https://v2.vuejs.org/v2/guide/typescript.html in my tsconfig.json I have:

"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: [] has never[] type.

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


为了补充约书亚的答案,您可能需要声明内联玩家的类型,这样当数据变大时,您的代码就不会变得太冗长。

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

另外一个选择:

data() {
  return {
    players: new Array<Player>()
  };
},
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Typescript 设置 Vue 数据对象中的数据类型 的相关文章

随机推荐