跳到主要内容

接口与类型别名

描述对象形状是日常最高频操作。interface 与 type 都能做,习惯略有不同。

interface​

interface User {
id: number;
name: string;
email?: string; // 可选
readonly createdAt: Date; // 只读
}

const u: User = {
id: 1,
name: "Ada",
createdAt: new Date(),
};

interface 可以声明合并(同名合并字段),适合扩展库类型。

type 别名​

type ID = string | number;
type Point = { x: number; y: number };
type Handler = (event: string) => void;

type 可表达联合、交叉、映射等;不能声明合并。

怎么选​

场景倾向
对象形状、可被第三方扩展interface
联合 / 交叉 / 工具类型组合type
团队统一一种也行对象用 interface,其余用 type 即可

交叉与扩展​

interface Timestamped {
createdAt: Date;
}

interface Post extends Timestamped {
title: string;
}

type Admin = User & { role: "admin" };

索引签名(点到为止)​

interface Dict {
[key: string]: number;
}

开放索引会削弱具体字段检查,能写清字段时优先写清。

要点​

  1. 可选 ?、只读 readonly
  2. interface vs type:对象扩展 vs 类型表达式
  3. extends / & 做组合
  4. 少用宽松索引签名