高级 Generic 模式
Master 高级 generics: constraints, defaults, variadic tuples, and recursive 类型.
你将学到
- Generic constraints 使用 extends and keyof 运算符
- 默认类型参数 and multi-level generics
- Variadic tuple 类型 for flexible 函数 signatures
- Recursive 类型 for 树 and 链接-列表结构
概念讲解
Constraints and keyof
Generic constraints limit what a type parameter can be. <T extends 字符串> requires T to be a string or subtype. The most powerful constraint uses keyof: <T, K extends keyof T> ensures K is a valid key of T. This lets you write functions like 函数 获取<T, K extends keyof T>(obj: T, 键: K): T[K] that are fully type-safe — the return type matches the property type at the given key.
Default Type Parameters
Generic type parameters can have defaults: 接口 Box<T = 字符串> { 值: T; }. If you use Box without a type argument, T defaults to 字符串. Defaults are useful when a type is usually a specific value but occasionally varies. They also appear in utility types: 部分<T> has no default, but 记录<K, T> could default K to 字符串.
Variadic and Recursive Types
Variadic tuple types let you spread generic tuples: type Push<T extends unknown[], V> = [...T, V] appends V to any tuple. This enables type-safe concat, push, and other array operations. Recursive types reference themselves: type Json = string | number | boolean | null | Json[] | { [key: string]: Json } describes arbitrary JSON. These advanced patterns power libraries like zod and tRPC that build complex types from simple primitives.
示例代码
// keyof constraint — K must be a key of T, return type is T[K].
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Alice", age: 30 };
const id = getProperty(user, "id"); // number
const name = getProperty(user, "name"); // string
// Default type parameter.
interface Response<T = string> {
data: T;
status: number;
}
const text: Response = { data: "hello", status: 200 };
const nums: Response<number[]> = { data: [1, 2, 3], status: 200 };
// Variadic tuple — append a type to a tuple.
type Push<T extends unknown[], V> = [...T, V];
type Pair = Push<[number, string], boolean>; // [number, string, boolean]
// Recursive type — describe arbitrary JSON.
type Json =
| string
| number
| boolean
| null
| Json[]
| { [key: string]: Json };
const data: Json = { name: "Alice", tags: ["a", "b"], meta: { active: true } };
console.log(id, name, text.data, nums.data, data);
Constraints (extends keyof T) ensure 类型-safe 属性 access. 默认类型参数 provide fallbacks. Variadic tuples spread generic 数组. Recursive 类型引用它们自己 for 树-如结构.
动手试一试
- JSON 到 TypeScript
Recursive 类型如 JSON 描述 arbitrary nested JSON 结构.
- JSON Validator
验证复杂 nested 数据针对 recursive 类型 shapes.
常见错误
错误写法
Overcomplicating 类型使用 deep recursive generics 那个是 困难到 调试
正确做法
Keep generics as 简单 as 可能. 如果类型 produces confusing 错误消息, simplify 它. 类型-level 复杂度有 maintenance cost — 仅 use 高级模式当 它们 provide 清晰值.
错误写法
Forgetting 到 constrain generics and 获取 '类型任何是 不 assignable' 错误
正确做法
添加 constraints 使用 extends. 不使用 constraints, T 是 treated as unknown or 任何 in 许多上下文, leading 到类型错误. Constrain T 到 shape 你需要.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。