第 35 期 - TypeScript's Array[number] Syntax for Extracting Array Element Types
logoFRONTALK AI/11月27日 16:31/阅读原文

摘要

文章以示例代码详细介绍了 TypeScript 中 Array[number]语法,它可用于提取数组元素类型,还阐述了该语法的工作原理、应用场景及相关概念。

一、示例引入

在 TypeScript 中有个奇特的语法Array[number]。例如,先定义一个常量数组roles,像这样:

const roles = ["admin", "editor", "contributor"] as const;

然后通过typeof获取其类型,再使用RolesAsType[number]得到数组元素的类型。

二、更简单的示例

  1. 定义测试数据数组 先定义一个可能用于测试的数组possibleResponses
const possibleResponses = [
  {
    status: 200,
    body: "Hello, world!",
  },
  {
    status: 404,
    body: "Not found",
  },
  {
    status: 500,
    body: "Internal server error",
  },
];
  1. 提取数组类型 通过typeof获取possibleResponses的类型,它是一个包含statusbody属性的对象数组。如果想要去除数组部分,只得到对象的类型,可以使用Array[number]这个看起来很神秘的技巧。
type PossibleResponses = typeof possibleResponses;
type PossibleResponse = PossibleResponses[number];

三、语法原理

  1. 索引访问类型 这种语法是一种索引访问类型,是访问类型属性的一种方式。简单来说,就像从一个对象中获取属性一样,例如:
type NavbarProps = {
  onChange: () => void;
};
type OnChangeType = NavbarProps["onChange"];
  1. 传递 number 的意义 当把number传递给索引访问类型时,就表示获取对象中所有用数字键访问的属性。可以通过一个有字符串键和数字索引签名的对象来演示:
type ExampleObj = {
  // String keys
  stringKey1: "string-key";
  stringKey2: "string-key";
  // Numeric index signature
  [key: number]: "number-key";
};
type NumericValuesOnly = ExampleObj[number];

四、应用场景

  1. 库代码中的应用 这个技巧在库代码中很有用。
  2. 从数组构建枚举 在从数组构建自己的枚举时也很棒,像第一个例子那样。不过要注意,在第一个例子中roles被标记为const,这使得 TypeScript 能够推断出数组的字面量值,如果没有这个标记,TypeScript 会推断为string[]类型。
const roles = ["admin", "editor", "contributor"];
type RolesAsType = typeof roles;
type Role = RolesAsType[number];

五、总结

总的来说,Array[number]在 TypeScript 中是用于提取对象的所有数字键的,对于数组来说,就是提取数组成员的类型。这是一个从值派生类型的强大概念。

 

扩展阅读

Made by 捣鼓键盘的小麦 / © 2025 Front Talk 版权所有