泛型是 TypeScript 的说法:「我不在乎你用什么类型,但你给我什么,我就还给你什么。」这是抽象的概念,完美映射到自然英语中。
Generics are TypeScript's way of saying 'I don't care what type you use, but whatever you give me, I'll give you back the same.' It's the concept of abstraction — and it maps perfectly to natural English.
代码精读
// Problem: writing the same function for every type is repetitive
function firstString(arr: string[]): string { return arr[0]; }
function firstNumber(arr: number[]): number { return arr[0]; }
// Solution: Generics — one function, any type
// Read T as 'whatever type you bring'
function first<T>(arr: T[]): T {
return arr[0];
}
// Usage — TypeScript infers T automatically:
const word = first(['hello', 'world']); // T = string
const num = first([1, 2, 3]); // T = number
const user = first([{ name: 'Alice' }]);// T = { name: string }
// Real-world generic: a type-safe wrapper
interface ApiResponse<T> {
data: T;
success: boolean;
message: string;
}
// Now you can have: ApiResponse<User>, ApiResponse<Lesson>, etc.
💡 建议:把每一行代码大声用英文念出来,注释就是你的翻译。
单词讲解
generic
/dʒəˈnɛrɪk/
adjective / noun
通用的;泛型
infer
/ɪnˈfɜːr/
verb
推断,推导
repetitive
/rɪˈpɛtɪtɪv/
adjective
重复性的,单调的
abstraction
/æbˈstrækʃn/
noun
抽象(隐藏细节,暴露核心逻辑)
理解检验
先在脑子里想一想——再点开看参考答案。
Q1: In your own words, what does `T` represent in `function first<T>(arr: T[]): T`?
Q2: What is the benefit of `ApiResponse<T>` over a plain object?
核心要点▼ 展开