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.

泛型是 TypeScript 的说法:「我不在乎你用什么类型,但你给我什么,我就还给你什么。」这是抽象的概念,完美映射到自然英语中。

📖Read the Code

// 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.

💡 Tip: read each line aloud in English. The comments are your guide.

📚Vocabulary Focus

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
抽象(隐藏细节,暴露核心逻辑)

🧠Comprehension Check

Answer in your head first — then reveal to see the model answer.

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?
💡Key Insight▼ Reveal