我正在尝试创建一个对象数组,例如:
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)
我该如何解决这个错误?
objectExmaple
是一个对象,而不是一个数组,因此您需要使用{}
. 此外,如果您希望 keya
拥有一个数组,则需要将其放在 init 或使用之前push
:
const objectExmaple: { [key: string]: { [key: string]: string | boolean }[] } = {
a: []
};
objectExmaple['a'].push({ id: 'john', detail: true });
objectExmaple['a'].push({ id: 'james', detail: false});
该类型也可以更清晰地写成 Record<string, Array<Record<string, string | boolean>>>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句