TypeScript 对象类型、type 与 interface
解释 TypeScript 如何描述对象形状,以及 type alias 与 interface 在组合、扩展和声明合并上的边界。
#type / concept
#status / evergreen
#tech / dev
#resource / typescript
[!info] related notes
- 路线:TypeScript 学习路线
- 兼容模型:TypeScript 结构化类型与函数兼容性
- 高级组合:TypeScript 高级类型
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。 - 同一模块保持一致比争论“永远用哪个”更重要。
- 不要依赖意外的声明合并;全局扩展应明确记录。