Skip to content

Generic

一句话解释

generic 是类型变量 (如 T) 那个 lets 你编写函数, 类, and 类型那个工作使用任何类型虽然 preserving 类型 safety.

用大白话说

Generics are type variables. Instead of writing a function for each type, you write one function with a type parameter (usually called T) that the caller specifies. This makes code reusable without sacrificing type safety.

例如, identity<T>(x: T): T works with any type — pass a number, get a number; pass a string, get a string. The type relationship between input and output is preserved, which would be lost if you used 任何.

Generics are used everywhere in TypeScript: in arrays (Array<T>), in Promises (Promise<T>), in Map (Map<K, V>), and in most utility types. You can constrain generics with extends to limit what types are allowed.

示例

typescript
function identity<T>(value: T): T {
  return value;
}

const num = identity(42);     // T inferred as number
const str = identity("hi");  // T inferred as string

// Constrained generic
function getLength<T extends { length: number }>(x: T): number {
  return x.length;
}

identity 工作使用任何类型. getLength 需要 T 到有 长度属性.

相关术语

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表