在Typescript中将给定类型的数组声明为Object中定义的键的值的语法是什么?

问题描述 投票:0回答:1

我正在尝试在vuex中向我们的state对象添加属性。此属性是一个数组,稍后有对象被推入该数组。

store.ts

  state: {
    spudIsAnimating: false,
    selectedColor: colors[0],
    addedElements: object[] = [],
  },
  addToElements(state, element: object){
    state.addedElements.push(element);
  },

这将显示错误[ts] Cannot find name 'object'. Did you mean 'Object'? [2552][ts] Argument of type 'object' is not assignable to parameter of type 'never'.

store.ts

addedElements: Object[] = [],

这给出了argument of type...错误,以及新的错误ts] Element implicitly has an 'any' type because type 'ObjectConstructor' has no index signature. [7017].

store.ts

addedElements: Object[],

这解决了argument of type...错误,但仍然存在index signature错误。

store.ts

addedElements: Array<Object>,

这将显示错误[ts] Operator '<' cannot be applied to types 'ArrayConstructor' and 'ObjectConstructor'.。此外,addToElement函数现在具有以下错误:ts] Property 'push' does not exist on type 'boolean'. [2339]

我只是想遵循documentation中的语法准则:

TypeScript,就像JavaScript,允许您使用值数组。数组类型可以用以下两种方法之一编写。首先,您使用元素的类型,然后使用[]表示该元素类型的数组:

let list: number[] = [1, 2, 3]; 

第二种方法使用通用数组类型Array:

let list: Array<number> = [1, 2, 3];

在文档的任何地方都找不到关于“声明对象内的数组值”的说明。

typescript
1个回答
0
投票

addedElements: Array<any>或等价的addedElements: any[]

(由于TsLint,首选第一种语法)

© www.soinside.com 2019 - 2024. All rights reserved.