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

时间:2017-12-14 09:44:17

标签: typescript vue.js vuejs2

我目前正在webpack项目中使用带有Typescript的Vue.js。

正如我!\"#$%&'()*+,-./0123456789:中的Recommended Configuration所示:

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: []类型。

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

5 个答案:

答案 0 :(得分:17)

要添加Joshua的答案,您可能需要声明内联播放器的类型,这样您的代码就不会因为数据变大而变得过于冗长。

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

答案 1 :(得分:4)

您的:type-at方法具有未声明的返回值。

如果您提供一个,TypeScript将知道data会发生什么。

您只需展开players行。

e.g:

data() {

需要成为:

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

多田!玩家现在是任何类型的阵列。

答案 2 :(得分:2)

禁止使用'<>'语法的类型声明。改为使用“ as”语法。

它看起来像这样:

players: [] as Player[]

答案 3 :(得分:2)

我发现了另一种与典型语法更接近的方法,同时使代码简短。

data() {
  return new class {
    players: Player[] = []
  }();
},

答案 4 :(得分:0)

这应该有效:

declare interface Player {
  cod: string,
  param: string
}

declare interface BaseComponentData {
  players: {name: string}[]
}

export default Vue.extend({
  name: 'basecomponent',
  data(): BaseComponentData {
    return {
      players: []
    };
  },
})