Generics in TypeScript
编写 reusable, 类型-safe 函数 and 类型 using generic 类型参数.
你将学到
- 什么 generics 是 and 为什么它们是 called 类型参数
- 如何 编写 generic 函数 and 接口
- Constraining generics 使用 extends keyword
- Using 多个类型参数 in 单个定义
概念讲解
The Problem Generics Solve
想象 a function that returns the first element of an array. Without generics, you would type it as 函数 首先(arr: 任何[]): 任何 — but then the return type is 任何, losing all type information. Generics solve this by letting you declare a type variable that represents the element type: 函数 首先<T>(arr: T[]): T. When called with 数字[], TypeScript infers T = 数字 and the return type is 数字. The function is reusable and type-safe.
Generic Syntax
You declare type parameters in angle brackets: <T> for one, <T, U> for two. They can appear in parameter types, return types, and the function body. Generic interfaces work the same way: 接口 Box<T> { 值: T; }. Generic classes are common for data structures like stacks and queues: 类 Stack<T> { 推送(项: T): 空; }.
Constraining Generics
Sometimes a generic type needs to have certain properties. You constrain it with extends: <T extends { 长度: 数字 }> means T must have a 长度 property. This lets you access 项.长度 inside the function. The keyof operator is often used in constraints: <K extends keyof T> ensures K is a valid key of type T.
示例代码
// Generic function — T is inferred from the argument.
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
// Generic interface — describes a container holding any type.
interface Box<T> {
value: T;
}
// Constrained generic — T must have a 'length' property.
function getLength<T extends { length: number }>(item: T): number {
return item.length;
}
// Generic with keyof constraint — K must be a key of T.
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const nums = first([10, 20, 30]); // T inferred as number
const strs = first(["a", "b", "c"]); // T inferred as string
const box: Box<string> = { value: "hello" };
console.log(nums, strs, box.value);
console.log(getLength("hello"), getLength([1, 2, 3]));
console.log(getProperty({ name: "Alice", age: 30 }, "name"));
Generics (<T>) 是类型变量 inferred 从 usage. 它们制作函数 reusable 不使用 losing 类型 safety. Constraints (extends) 限制什么 T 能是 and let 你 access 它的属性.
动手试一试
- JSON 到 TypeScript
Generic 模式如 Box<T> and 响应<T> 是常见 in 输入 APIs.
- JSON Formatter
格式 generic 数据结构到 理解它们的 shapes.
常见错误
错误写法
Using 任何相反的 generics for reusable utility 函数
正确做法
Generics preserve 类型信息通过函数. Replace 任何使用类型参数 <T> 所以输出类型 reflects 输入类型.
错误写法
Forgetting 到 constrain generics 当 accessing 特定属性
正确做法
如果你 access 项.长度内部 generic 函数, constrain T 使用 <T extends { 长度: 数字 }>. 不使用 constraint, 编译器 cannot 验证属性 exists.
练习 Generics in TypeScript
10 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。