接口与类型别名
约 257 字小于 1 分钟
2026-02-09
两者都能描述对象结构
interface UserByInterface {
id: number
name: string
}
type UserByType = {
id: number
name: string
}核心差异
| 对比点 | interface | type |
|---|---|---|
| 主要用途 | 描述对象/类契约 | 类型表达能力更广 |
| 联合类型 | 不擅长 | 强项(`A |
| 交叉类型 | 可通过 extends 间接实现 | 强项(A & B) |
| 声明合并 | 支持 | 不支持 |
| 条件类型 / 映射类型 | 不支持直接声明 | 强项 |
声明合并(interface 特有)
interface RequestContext {
traceId: string
}
interface RequestContext {
userId: string
}
const ctx: RequestContext = {
traceId: 't_1',
userId: 'u_1',
}继承与组合
interface 继承
interface Animal {
name: string
}
interface Dog extends Animal {
bark: () => void
}type 组合
type Animal = { name: string }
type Dog = Animal & { bark: () => void }约束函数
interface Predicate {
(value: number): boolean
}
const isPositive: Predicate = (value) => value > 0类实现接口
interface Runner {
run: () => void
}
class Person implements Runner {
run() {
console.log('running')
}
}实践建议
- 业务对象契约优先用
interface(便于扩展、声明合并) - 联合、映射、条件类型优先用
type - 不要机械地“只用一种”,按语义选型
