TypeScript 对象类型、type 与 interface

解释 TypeScript 如何描述对象形状,以及 type alias 与 interface 在组合、扩展和声明合并上的边界。

#type / concept #status / evergreen #tech / dev #resource / typescript

[!info] related notes

TypeScript 对象类型、type 与 interface

一句话定义

对象类型描述值必须具备哪些属性;interface 专注可扩展的对象契约,type 可以给任意类型表达式命名并参与联合、交叉和映射。

interface StreamIds {
  runId?: string;
  messageId?: string;
}

type RunStatus = 'idle' | 'running' | 'failed';
type RunSnapshot = StreamIds & { status: RunStatus };

共同能力

两者都能描述对象、被扩展或组合,也都依据结构而不是名字判断兼容性。普通业务对象多数情况下任选其一都能工作。

主要差异

  • interface 支持声明合并,适合需要开放扩展的公共对象契约。
  • type 能直接表示联合、元组、条件类型和映射类型。
  • interface A extends B 强调对象继承关系。
  • type A = B & C 强调类型表达式组合。

可选与只读

interface EventIds {
  readonly runId: string;
  interactionId?: string;
}

readonly 是编译期写入限制,不会冻结运行时对象。? 表示属性可能缺失;开启 exactOptionalPropertyTypes 后,缺失与显式 undefined 会被更准确地区分。

决策规则

  • 对象公共契约且希望可扩展:优先 interface
  • 联合、元组、工具类型或类型计算:使用 type
  • 同一模块保持一致比争论“永远用哪个”更重要。
  • 不要依赖意外的声明合并;全局扩展应明确记录。
创建于 2026/7/29 更新于 2026/7/29