HarmonyOS 鸿蒙Next: interface和class在TypeScript中的使用场景有哪些?
HarmonyOS 鸿蒙Next: interface和class在TypeScript中的使用场景有哪些? 在实际开发中,如何根据具体情况选择使用 interface 还是 class?
2 回复
在 TypeScript 中,“interface” 和 “class” 是两种不同的概念,它们的使用场景和核心用途有明显区别。以下是具体分析及选择建议:
一、核心区别
特性 | interface | class |
---|---|---|
实现 | 纯类型定义,无运行时代码 | 既是类型定义,也是运行时构造函数 |
实例化 | 不能直接实例化 | 可通过 new 实例化 |
方法实现 | 只能定义签名,无具体实现 | 可定义具体方法实现 |
继承 | 支持 extends 多继承其它接口 | 单继承类,但可多实现接口 |
合并声明 | 同名接口会自动合并 | 同名类会报错 |
编译后代码 | 完全消失(纯类型) | 保留为 JS 类 |
二、使用场景对比
- 优先使用 “interface”的场景
- 定义数据模型 (DTO/Props)
如 API 响应结构、React 组件 Props 等纯数据类型的描述:
interface User {
id: number;
name: string;
email?: string; // 可选属性
}
// React 组件 Props
interface ButtonProps {
text: string;
onClick: () => void;
}
- 声明函数类型或复杂类型
定义函数签名、索引类型、联合类型等:
interface SearchFunc {
(source: string, keyword: string): boolean;
}
interface Dictionary {
[key: string]: number;
}
- 扩展第三方库类型
通过声明合并为已有类型添加新属性:
// 扩展 Window 类型
interface Window {
myCustomProp: string;
}
- 多继承场景
TypeScript 接口支持多重继承:
interface Shape {
color: string;
}
interface Transparent {
opacity: number;
}
interface Circle extends Shape, Transparent {
radius: number;
}
- 优先使用
class
的场景
- 封装业务逻辑
需要包含方法实现和状态管理时:
class Calculator {
private value: number = 0;
add(n: number): this {
this.value += n;
return this;
}
getResult(): number {
return this.value;
}
}
- 需要实例化对象
创建具有明确行为和数据的对象:
class Animal {
constructor(public name: string) {}
move(distance: number = 0) {
console.log(`${this.name} moved ${distance}m`);
}
}
- 利用 OOP 特性
继承、多态、访问控制等面向对象特性:
class Bird extends Animal {
fly(height: number) {
console.log(`${this.name} flew ${height}m high`);
}
}
- 使用装饰器
Class 是装饰器的主要应用场景:
@sealed
class Report {
//...
}
- 需要运行时类型检查
通过 instanceof
进行类型守卫:
if (animal instanceof Bird) {
animal.fly(100);
}
三、选择策略(决策树)
- 是否需要方法实现?
- ✅ 需要具体实现 →
class
- ❌ 仅类型定义 →
interface
- 是否需要实例化?
- ✅ 需要
new
创建对象 →class
- ❌ 只是类型描述 →
interface
- 是否需要扩展第三方类型?
- ✅ 通过声明合并 →
interface
- 是否需要多重继承?
- ✅ 接口多继承 →
interface
- 是否使用装饰器?
- ✅ 类装饰器 →
class
- 是否进行运行时类型检查?
- ✅
instanceof
→class
四、协同工作示例
// 用接口定义契约
interface Serializable {
serialize(): string;
}
// 类实现接口
class User implements Serializable {
constructor(public name: string, public age: number) {}
serialize(): string {
return JSON.stringify(this);
}
}
// 函数接收接口类型参数
function saveData(obj: Serializable) {
localStorage.setItem('data', obj.serialize());
}
五、最佳实践建议
- 优先用 “interface” 描述数据结构(除非需要类特性)
- 用 “class” 封装具有行为的实体
- 接口用于定义公共契约(如组件 Props、API 响应)
- 类用于实现具体业务逻辑
- 利用“implements”明确类与接口的关系
通过理解二者的核心差异,结合具体场景的需求(是否需要实现、是否需要实例化等),可以更精准地选择合适的方式。
更多关于HarmonyOS 鸿蒙Next: interface和class在TypeScript中的使用场景有哪些?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html