作为一个新手,我正在努力为在运行时具有以下值的对象创建typescript类型定义:
{ "animals" :
[
{
name: "kittie",
color: "blue"
},
{
name: "bruno",
color: "green"
}
],
"people" :
[
{
name: "paul",
color: "blue"
},
{
name: "carla",
color: "green"
}
]
};
内部数组可以定义为:
people: { name: string, color: string}[];
但是我如何定义整个对象呢?
答案 0 :(得分:3)
您可以创建2个类型/接口,并将该接口用于对象界面内的内部对象。
interface InnerObject {
name: string;
color: string;
}
interface OuterObject {
animals: InnerObject[];
people: InnerObject[];
}
或者,如果您希望OuterObject
的键是动态的:
interface InnerObject {
name: string;
color: string;
}
interface OuterObject {
[key: string]: InnerObject[];
}
与使用内置类型Record
:
Record<string, InnerObject[]>