迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > TypeScript >

从 TypeScript 中的数组类型获取元素类型

作者:迹忆客 最近更新:2023/01/12 浏览次数:

要从数组类型中获取元素类型,请使用带有 infer 声明的条件类型来推断数组中元素的类型。 TypeScript 会填入元素的类型,我们可以在条件类型的 true 分支中返回。

type ArrElement<ArrType> = ArrType extends readonly (infer ElementType)[]
  ? ElementType
  : never;

const arr1 = ['a', 'b'];

// 👇️ type T1 = string
type T1 = ArrElement<typeof arr1>;

const arr2 = ['a', 1];

// 👇️ type T2 = string | number
type T2 = ArrElement<typeof arr2>;

类型别名采用数组类型的泛型。

我们使用了条件类型,数组的类型扩展了数组元素的推断类型。

条件类型与三元运算符非常相似。

如果问号前的表达式计算结果为真,我们返回冒号前的类型,否则返回冒号后的类型。

这是条件类型如何工作的示例。

interface Person {
  name: string;
}

interface Employee extends Person {
  id: number;
}

// 👇️ string
type T3 = Employee extends Person ? string : number;

我们使用 infer 关键字让 TypeScript 填充数组元素的类型并返回它。

这是原始示例中条件类型如何工作的过度简化版本。

// 👇️ type T10 = string
type T10 = string[] extends string[] ? string : never;

这是原始代码片段。

type ArrElement<ArrType> = ArrType extends readonly (infer ElementType)[]
  ? ElementType
  : never;

const arr1 = ['a', 'b'];

// 👇️ type T1 = string
type T1 = ArrElement<typeof arr1>;

目前,没有什么可以阻止类型传递给不是数组的泛型。

我们可以使用类型保护来确保类型别名仅用于数组。

type ArrElement<ArrType extends readonly unknown[]> =
  ArrType extends readonly (infer ElementType)[] ? ElementType : never;

const str = 'hello';

// ⛔️ Error: Type 'string' does not satisfy
// the constraint 'readonly unknown[]'.ts(2344)
type T1 = ArrElement<typeof str>;

TypeScript 错误 Type 'string' does not satisfy the constraint

现在传入的泛型只能是扩展 unknown[] 的类型,换句话说,一个包含任何类型元素的数组。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Arduino 数组长度

发布时间:2024/03/13 浏览次数:239 分类:C++

可以使用 sizeof()函数获得数组的长度。

在 Python 中将 Tensor 转换为 NumPy 数组

发布时间:2024/03/12 浏览次数:131 分类:Python

在 Python 中,可以使用 3 种主要方法将 Tensor 转换为 NumPy 数组:Tensor.numpy()函数,Tensor.eval()函数和 TensorFlow.Session()函数。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便