Conditional 类型
一句话解释
conditional 类型 (T extends U ? X : Y) 选择类型 X 如果 T 是 assignable 到 U, 否则类型 Y. 它启用类型-level programming.
用大白话说
conditional 类型是 如如果-else at 类型 level. T extends U ? X : Y means: if T is assignable to U, the type is X; otherwise it is Y.
Conditional types are powerful for type-level computation. They can distribute over unions, infer type parameters with infer, and create complex type transformations.
The built-in 排除<T, U>, Extract<T, U>, and NonNullable<T> are all conditional types. They are used in advanced TypeScript libraries for deriving types from other types automatically.
示例
typescript
type IsString<T> = T extends string ? "yes" : "no";
type A = IsString<string>; // "yes"
type B = IsString<number>; // "no"
type NonNullable<T> = T extends null | undefined ? never : T;IsString 检查如果 T 是字符串. NonNullable 移除空 and undefined 从 T.
相关术语
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。