创建一个包含多个对象的数组类型



我想为一个对象数组创建一个类型。对象数组可以像这样:

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个对象

在为数组设置类型时,应该采用以下格式:any[].

那么在你的例子中

export type trollType = { [key: string]: string }[];

您可以尝试使用Record类型来存储对象属性定义并从中创建一个数组,如下所示:

type TrollType = Record<string, string>[];
const troll: TrollType = [
{
a: 'something',
b: 'something else'
},
{
a: 'something',
b: 'something else'
}
];

最新更新