TypeScript 高级类型与模式

TypeScript 高级类型与模式

条件类型

type IsString<T> = T extends string ? "yes" : "no";

映射类型

type Readonly<T> = { readonly [P in keyof T]: T[P]; };

可辨识联合模式

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "rectangle"; width: number; height: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle": return Math.PI * shape.radius ** 2;
    case "rectangle": return shape.width * shape.height;
    default: const _: never = shape; return _;
  }
}

掌握这些高级类型模式,能让你的 TypeScript 代码既灵活又安全。

comments powered by Disqus