从 TypeScript 中的数组类型获取元素类型
Get the Element type from an Array type in TypeScript
要从数组类型中获取元素类型:
- 使用带有声明的条件类型
infer
来推断数组中元素的类型。 - TypeScript 会填写元素的类型,我们可以在
true
条件类型的分支中返回它。
索引.ts
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>;
类型别名使用泛型获取数组的类型。
我们
在示例中使用了条件类型。
条件类型与三元运算符非常相似
。
If the expression before the question mark evaluates to a true, the type before the colon is returned, otherwise, the type after the colon is returned.
# Using conditional types
Here is an example of how conditional types work.
index.ts
interface Person { name: string; } interface Employee extends Person { id: number; } // 👇️ string type T3 = Employee extends Person ? string : number;
We used the
infer
keyword to have TypeScript fill in the type of the array element.
Here is an oversimplified version of how the conditional type in the original
example works.
index.ts
// 👇️ type T10 = string type T10 = string[] extends string[] ? string : never;
And here is the original code sample.
index.ts
type ArrElement<ArrType> = ArrType extends readonly (infer ElementType)[] ? ElementType : never; const arr1 = ['a', 'b']; // 👇️ type T1 = string type T1 = ArrElement<typeof arr1>;
At the moment, there is nothing that prevents the type from getting passed a
generic that is not an array.
You can use a type guard to make sure
that the type alias is only used with an array.
index.ts
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>;
现在传入的泛型只能是 extends 的类型unknown[]
,换句话说,一个包含任何类型元素的数组。