跳到主要内容

泛型

泛型让类型像函数参数一样可复用,同时保持调用处的精确类型。

泛型函数​

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

const n = identity(1); // number
const s = identity("hi"); // string

约束与默认参数​

function pickLength<T extends { length: number }>(x: T): number {
return x.length;
}

function wrap<T = string>(x: T): T[] {
return [x];
}

extends 约束「至少具备这些成员」;默认类型参数减少调用处啰嗦。

泛型接口与类​

interface ApiResponse<T> {
data: T;
ok: boolean;
}

class Box<T> {
constructor(public value: T) {}
}

多个类型参数​

function mapPair<A, B>(a: A, b: B): [A, B] {
return [a, b];
}

先写具体例子,再抽象成泛型;避免一上来三个以上类型参数。

要点​

  1. <T> 在调用时被推断或显式传入
  2. T extends X 做约束
  3. 接口 / 类同样可泛型化
  4. 参数个数克制,可读性优先