Skip to content

Conditional 类型 in TypeScript

分支类型 at 编译时间使用 T extends U ? X : Y and infer keyword.

你将学到

  • 如何 T extends U ? X : Y 选择类型 based on 条件
  • Using infer keyword 到 extract 类型从 generic 参数
  • Distributive conditional 类型 over unions
  • 构建 reusable 类型-level utilities 使用 conditionals

概念讲解

The Conditional Syntax

A conditional type selects between two types based on whether one extends another: T extends U ? X : Y. If T is assignable to U, the result is X; otherwise, it is Y. This is like a ternary expression but at the type level. For example, 类型 IsString<T> = T extends 字符串 ? 真 : 假 produces 真 when T is a string and 假 otherwise. Conditional types let you write logic that the compiler evaluates during type checking.

The infer Keyword

The infer keyword extracts a type from within another type, but only inside the extends clause of a conditional. For example, 类型 Unbox<T> = T extends 数组<infer U> ? U : T extracts the element type if T is an array, otherwise returns T. This is how ReturnType<T> is implemented: T extends (...args: 任何) => infer R ? R : 从不 extracts the return type R from a function type. The infer keyword is essential for unwrapping and reverse-engineering types.

Distributive Conditionals

When a conditional type's checked type is a naked type parameter (not wrapped in another type), it distributes over unions. T extends U ? X : Y with T = | B evaluates as (extends U ? X : Y) | (B extends U ? X : Y). This distribution is usually what you want, but it can be surprising. To prevent distribution, wrap the type parameter: [T] extends [U] ? X : Y.

示例代码

              // Basic conditional — check if T is a string.
type IsString<T> = T extends string ? true : false;
type A = IsString<"hello">; // true
type B = IsString<42>;      // false

// infer — extract the element type of an array.
type ElementOf<T> = T extends (infer U)[] ? U : never;
type Num = ElementOf<number[]>;   // number
type Str = ElementOf<string[]>;   // string

// infer — extract return type of a function.
type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
type R = MyReturnType<() => string>; // string

// Distributive conditional — applies to each union member.
type ToArray<T> = T extends any ? T[] : never;
type Result = ToArray<string | number>; // string[] | number[]

// Non-distributive — wrap in a tuple to prevent distribution.
type NonDist<T> = [T] extends [any] ? T[] : never;

const check: A = true;
const elem: Num = 42;
console.log(check, elem);
            

Conditional 类型 (T extends U ? X : Y) 分支 at 类型 level. infer keyword extracts 类型从 generic 参数. Naked 类型参数 distribute over unions; wrapping in tuples prevents distribution.

动手试一试

  • JSON 到 TypeScript

    Conditional 类型 refine generated 类型 based on 字段 shapes.

  • Code Diff

    Compare 类型-level logic 使用它的运行时 equivalent.

常见错误

错误写法

Expecting conditional 类型到 evaluate at 运行时

正确做法

Conditional 类型是 编译-时间仅. 它们 produce 类型, 不值. For 运行时 branching, use regular 如果/else or 切换语句使用类型 guards.

错误写法

Forgetting 那个 naked 类型参数 distribute over unions

正确做法

T extends U ? X : Y distributes 当 T 是 naked 参数 over union. Wrap in [T] extends [U] 到 prevent distribution 如果你 想要到 treat union as 整个.

练习 Conditional 类型 in TypeScript

6 个练习

练习 Conditional 类型 in TypeScript

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误