主题
接口与对象类型
接口(interface
)是 TypeScript 中用于定义对象结构的核心机制,也可以使用 type
类型别名定义对象类型。本节将介绍它们的区别及实际用法。
interface 与 type 的区别
interface
ts
interface Person {
name: string;
age: number;
}
type
ts
type Person = {
name: string;
age: number;
};
区别总结:
特性 | interface | type |
---|---|---|
对象类型定义 | ✅ 支持 | ✅ 支持 |
联合类型 / 基本类型 | ❌ 不支持 | ✅ 支持 |
扩展方式 | extends | &(交叉类型) |
可重复定义并合并 | ✅ 支持(声明合并) | ❌ 不支持(会报错) |
实际开发中,推荐优先使用
interface
定义对象结构,使用type
处理联合类型或复杂组合。
可选属性、只读属性、索引签名
可选属性(?
)
ts
interface User {
name: string;
age?: number; // 可选
}
只读属性(readonly
)
ts
interface Config {
readonly port: number;
}
索引签名
用于动态定义属性:
ts
interface Dictionary {
[key: string]: string;
}
函数类型定义
接口和类型别名都可以用于函数签名声明:
ts
interface Add {
(a: number, b: number): number;
}
const add: Add = (x, y) => x + y;
或使用 type:
ts
type Subtract = (a: number, b: number) => number;