从 TypeScript 中的数组类型获取元素类型
要从数组类型中获取元素类型,请使用带有 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>;
现在传入的泛型只能是扩展 unknown[]
的类型,换句话说,一个包含任何类型元素的数组。
相关文章
将 NumPy 数组转换为 Pandas DataFrame
发布时间:2024/04/21 浏览次数:111 分类:Python
-
本教程介绍了如何使用 pandas.DataFrame()方法从 NumPy 数组生成 Pandas DataFrame。
如何将 Pandas Dataframe 转换为 NumPy 数组
发布时间:2024/04/20 浏览次数:176 分类:Python
-
本教程介绍如何将 Pandas Dataframe 转换为 NumPy 数组的方法,例如 to_numpy,value 和 to_records
在 Python 中将 Tensor 转换为 NumPy 数组
发布时间:2024/03/12 浏览次数:131 分类:Python
-
在 Python 中,可以使用 3 种主要方法将 Tensor 转换为 NumPy 数组:Tensor.numpy()函数,Tensor.eval()函数和 TensorFlow.Session()函数。
在 Python 中将 CSV 读取为 NumPy 数组
发布时间:2024/03/12 浏览次数:133 分类:Python
-
本教程演示如何在 Python 中将 CSV 读取为 NumPy 数组。