从 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[]
的类型,换句话说,一个包含任何类型元素的数组。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。