TypeScript 中 interface 和 type 的对比
·
本文同步发表于我的微信公众号,微信搜索 程语新视界 即可关注,每个工作日都有文章更新
在鸿蒙开发中,interface 和 type 都是用来定义类型的关键字,但它们有重要的区别。详细对比如下:
一、核心区别总结
| 特性 | interface | type |
|---|---|---|
| 扩展性 | 可通过 extends 继承 | 通过 & 交叉类型扩展 |
| 合并声明 | 支持声明合并 | 不支持 |
| 实现方式 | 类可通过 implements 实现 | 不能直接被类实现 |
| 原始类型 | 不能直接定义原始类型别名 | 可以定义原始类型别名 |
| 元组/联合类型 | 需要额外语法 | 原生支持 |
| 性能 | 检查速度略快 | 复杂类型时稍慢 |
二、语法差异
1. 基础定义
// interface 定义对象形状
interface User {
name: string;
age: number;
}
// type 定义类型别名
type UserType = {
name: string;
age: number;
};
2. 扩展方式
// interface 扩展
interface Admin extends User {
privileges: string[];
}
// type 扩展
type AdminType = UserType & {
privileges: string[];
};
三、实际应用差异
1. 组件 Props 类型定义
// 方案1: interface
interface ButtonProps {
text: string;
onClick: () => void;
}
// 方案2: type
type ButtonPropsType = {
text: string;
onClick: () => void;
};
@Entry
@Component
struct MyButton {
@Prop text: string = '';
@Prop onClick: () => void = () => {};
build() {
Button(this.text).onClick(this.onClick)
}
}
在Props定义中两者几乎等价
2. 与类的关系
// interface 可以被类实现
class UserImpl implements User {
name: string = '';
age: number = 0;
}
// type 定义的对象类型也可以被实现
class UserTypeImpl implements UserType {
name: string = '';
age: number = 0;
}
四、怎么选择?
优先使用 interface 的场景:
- 需要声明合并(如扩展第三方库类型)
- 需要被类
implements实现 - 定义对象类型且需要清晰的可读性
- 鸿蒙UI组件Props/State定义
优先使用 type 的场景:
- 需要定义联合类型、元组类型
type ID = string | number;
type Coord = [number, number];
2. 需要定义函数类型
type ClickHandler = (event: Event) => void;
五、开发建议
-
项目规范:
- 统一团队约定(如对象类型用interface,工具类型用type)
- 在
.eslintrc中配置首选类型规则
-
性能考量:
- 大型项目中使用interface可能获得更好的类型检查性能
- 复杂类型推导使用type更灵活
-
联合类型实践:
// 定义鸿蒙组件状态
type ComponentState =
| { status: 'loading' }
| { status: 'success', data: Item[] }
| { status: 'error', error: Error };
其实开发中,两者大部分情况下可以互换,关键是根据团队规范和具体场景选择最合适的工具。
更多推荐


所有评论(0)