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

标签 typescript

假设我有这样的类型:

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>将删除 undefinednull来自它的类型参数。

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/

相关文章:

reactjs - React 项目中的 typescript 不再识别 'as' 关键字

angular - 非法使用过滤器 typescript

Angular/TypeScript 将服务注入(inject)基类而不是子类

typescript - 如何将测试添加到现有的 Typescript 项目,并让它显示在测试资源管理器中?

reactjs - 在 React + Typescript 中将 ref 传递给 child

typescript - 如何使用 TypeScript API 将 tsconfig.json 编译成配置对象?

angular - (Angular 5) 错误 : control. registerOnChange 不是函数

javascript - Angular 应用程序的参数化

javascript - react + typescript : How to fix "return type ' Element[ ]' is not a valid JSX element."?

typescript - 如何定义对象属性值的类型