TypeScript 接口与类型别名

TypeScript 接口与类型别名

接口 (Interface) 是定义对象形状的核心方式:

interface User {
  id: number;
  name: string;
  email: string;
  age?: number;
  readonly createdAt: Date;
}

类型别名 (Type Alias) 适用于联合类型、交叉类型:

type UserID = string | number;
type Status = "active" | "inactive" | "pending";
type Admin = User & { role: "admin" };

原则:定义对象用 interface,联合/交叉类型用 type。

comments powered by Disqus