【发布时间】:2022-06-15 04:52:04
【问题描述】:
我想为对象数组创建一个类型。对象数组可能如下所示:
const troll = [
{
a: 'something',
b: 'something else'
},
{
a: 'something',
b: 'something else'
}
];
我尝试使用的类型是:
export type trollType = [{ [key: string]: string }];
然后我想使用这样的类型:
const troll: trollType = [
{
a: 'something',
b: 'something else'
},
{
a: 'something',
b: 'something else'
}
];
但我收到此错误:
Type '[{ a: string; b: string; }, { a: string; b: string; }]' is not assignable to type 'trollType'.
Source has 2 element(s) but target allows only 1
我可以这样做:
export type trollType = [{ [key: string]: string }, { [key: string]: string }];
但是假设我的对象数组将有 100 个对象。
【问题讨论】:
标签: javascript typescript