假设我有这样的类型:
type Person = {
firstName: string;
lastName: string;
contact: {
type: string;
value: string;
}[];
};
Run Code Online (Sandbox Code Playgroud)
如果我想要数组元素的类型contact,我可以使用索引访问类型,例如:
type Contact = User['contact'][number];
// same as type Contact = { type: string; value: string };
Run Code Online (Sandbox Code Playgroud)
本质上,“数组数字索引处的类型contacts”,也适用于嵌套对象。
但是,如果这是一个可选参数,例如:
type Person = {
firstName: string;
lastName: string;
contact?: {
type: string;
value: string;
}[];
};
Run Code Online (Sandbox Code Playgroud)
这(有效)报告了以下错误:
Type '{ type: string; value: string; }[] | undefined' has no matching index signature for type 'number'.ts(2537)
Run Code Online (Sandbox Code Playgroud)
如何在类型别名中“空检查”以获得嵌套类型?
typescript ×1