第3章:面向对象编程
接口
3.3.1 接口的基本概念
接口(Interface)是ArkTS中定义对象行为的抽象契约,它仅描述成员的结构(属性/方法签名),而不包含具体实现。通过接口可以实现多态性和代码解耦。
核心特性:
- 纯类型定义,编译后不生成JavaScript代码
- 支持可选属性和只读属性
- 可定义方法签名
- 类可以通过
implements关键字实现接口
3.3.2 接口的定义与实现
// 定义接口
interface IPerson {
readonly id: number; // 只读属性
name: string;
age?: number; // 可选属性
greet(): void; // 方法签名
}
// 类实现接口
class Student implements IPerson {
id: number;
name: string;
constructor(id: number, name: string) {
this.id = id;
this.name = name;
}
greet() {
console.log(`Hello, I'm ${this.name}`);
}
}
3.3.3 接口的高级用法
- 函数类型接口:
interface SearchFunc {
(source: string, keyword: string): boolean;
}
let mySearch: SearchFunc = function(src, kw) {
return src.indexOf(kw) > -1;
}
- 索引类型接口:
interface StringArray {
[index: number]: string;
}
let arr: StringArray = ["ArkTS", "TypeScript"];
- 接口继承:
interface Shape {
color: string;
}
interface Square extends Shape {
sideLength: number;
}
3.3.4 接口与类型别名的区别
| 特性 | 接口(interface) | 类型别名(type) |
|---|---|---|
| 扩展方式 | 使用extends继承 | 使用&交叉类型 |
| 声明合并 | 支持 | 不支持 |
| 实现约束 | 可通过implements | 不能直接实现 |
| 原始类型/联合类型 | 不能定义 | 可以定义 |
3.3.5 最佳实践
- 优先使用接口定义对象形状
- 使用
readonly约束不应被修改的属性 - 通过接口组合实现复杂类型定义
- 在组件通信中定义清晰的接口规范
示例:组件通信接口:
// 定义组件props接口
interface ButtonProps {
text: string;
onClick: () => void;
disabled?: boolean;
}
@Entry
@Component
struct MyButton {
@Prop props: ButtonProps
build() {
Button(this.props.text)
.onClick(this.props.onClick)
.disabled(this.props.disabled ?? false)
}
}
注意:ArkTS接口与TypeScript接口语法完全兼容,但会根据OpenHarmony运行时特性进行编译优化。
