接口与类型别名
typescript
理解 interface 与 type 的差异与用法,并学会在合适的场景选择其一。
概念定义
interface 用于描述对象形状,支持声明合并;type 更通用,可为联合、交叉、函数签名等起别名。
代码示例
接口与可选属性
JavaScript
interface User {
id: string;
name: string;
email?: string; // 可选
}
const u: User = { id: '1', name: 'Alice' };接口描述对象结构,可通过 ? 定义可选属性。
类型别名与联合/交叉
JavaScript
type ID = string | number;
interface Base { id: ID }
type WithTimestamp = Base & { createdAt: Date };type 可为联合与交叉类型起别名,便于复用与组合。
使用场景
- •对象结构:优先使用 interface,便于扩展与合并
- •复杂类型组合:使用 type 构造联合/交叉/映射类型
常见错误
- ⚠混用 interface 与 type 导致风格不一致
- ⚠忽视可选与只读(readonly)修饰符