首页 > 解决方案 > 打字稿类型 Never[] 不可分配给对象数组

问题描述

我正在尝试创建一个对象数组,例如:

objectExample[a].push({ id: john, detail: true });
objectExample[a].push({ id: james, detail: false});

const objectExample = {
   a = [ { id: john, detail: true}, 
         { id: james, detail: false}];
   }

如果我在打字稿中尝试这个:

const objectExmaple: { [key: string]: { [key: string]: string | boolean}[]} = [];

我在 objectType 上收到此错误:

Type 'never[]' is not assignable to type '{ [key: string]: { [key: string]: string | boolean; }[]; }'.
  Index signature is missing in type 'never[]'.ts(2322)

如何解决此错误?

标签: typescript

解决方案


有几个问题:

  • 如果它是一个对象objectExample,则无法初始化[]
  • 类型定义很复杂
type Item = { [key: string]: string | boolean}
// Same as type Item = { [key: string]: string | boolean}

const objectExample: Record<string, Item[]> = {
   a: [ { id: 'john', detail: true}, 
         { id: 'james', detail: false}]
}

objectExample.a.push({ id: 'john', detail: true });
objectExample.a.push({ id: 'james', detail: false});

是一个工作游乐场的链接


推荐阅读