如何对可选属性的子级使用索引访问类型?

eri*_*2k8 8 typescript

假设我有这样的类型:

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)

如何在类型别名中“空检查”以获得嵌套类型?

weg*_*gry 19

更新

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];
Run Code Online (Sandbox Code Playgroud)

https://www.typescriptlang.org/docs/handbook/utility-types.html#nonnullabletype

较旧的答案

Exclude当您需要深入了解时,您可以键入。

type Contact = Exclude<User['contact'], undefined>[number];
Run Code Online (Sandbox Code Playgroud)

这些文档围绕该主题并不是特别稳定,但https://www.typescriptlang.org/docs/handbook/utility-types.html是当前链接。