假设我有这样的类型:
type Person = {
firstName: string;
lastName: string;
contact: {
type: string;
value: string;
}[];
};
如果我想要 contact
数组的元素类型,我可以使用索引访问类型,例如:
type Contact = User['contact'][number];
// same as type Contact = { type: string; value: string };
本质上,“contacts
数组的数字索引处的类型”,也适用于嵌套对象。
但是,如果这是一个可选参数,例如:
type Person = {
firstName: string;
lastName: string;
contact?: {
type: string;
value: string;
}[];
};
这(有效)报告错误:
Type '{ type: string; value: string; }[] | undefined' has no matching index signature for type 'number'.ts(2537)
如何在类型别名中“空检查”以获得嵌套类型?
最佳答案
更新
NonNullable<T>
将删除 undefined
和 null
来自它的类型参数。
type Contact = NonNullable<User['contact']> // almost the same as the next type, but also excludes `null` from the union.
type Contact = Exclude<User['contact'], undefined>[number];
https://www.typescriptlang.org/docs/handbook/utility-types.html#nonnullabletype
旧答案
您可以Exclude
当您需要深入研究时键入。
type Contact = Exclude<User['contact'], undefined>[number];
有关该主题的文档不是特别稳定,但 https://www.typescriptlang.org/docs/handbook/utility-types.html是当前链接。
关于 typescript :如何为可选属性的子级使用索引访问类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69110544/