Tailwind CSSTailwind CSS
Home
  • Tailwind CSS 书籍目录
  • Vue 3 开发实战指南
  • React 和 Next.js 学习
  • TypeScript
  • React开发框架书籍大纲
  • Shadcn学习大纲
  • Swift 编程语言:从入门到进阶
  • SwiftUI 学习指南
  • 函数式编程大纲
  • Swift 异步编程语言
  • Swift 协议化编程
  • SwiftUI MVVM 开发模式
  • SwiftUI 图表开发书籍
  • SwiftData
  • ArkTS编程语言:从入门到精通
  • 仓颉编程语言:从入门到精通
  • 鸿蒙手机客户端开发实战
  • WPF书籍
  • C#开发书籍
learn
  • Java编程语言
  • Kotlin 编程入门与实战
  • /python/outline.html
  • AI Agent
  • MCP (Model Context Protocol) 应用指南
  • 深度学习
  • 深度学习
  • 强化学习: 理论与实践
  • 扩散模型书籍
  • Agentic AI for Everyone
langchain
Home
  • Tailwind CSS 书籍目录
  • Vue 3 开发实战指南
  • React 和 Next.js 学习
  • TypeScript
  • React开发框架书籍大纲
  • Shadcn学习大纲
  • Swift 编程语言:从入门到进阶
  • SwiftUI 学习指南
  • 函数式编程大纲
  • Swift 异步编程语言
  • Swift 协议化编程
  • SwiftUI MVVM 开发模式
  • SwiftUI 图表开发书籍
  • SwiftData
  • ArkTS编程语言:从入门到精通
  • 仓颉编程语言:从入门到精通
  • 鸿蒙手机客户端开发实战
  • WPF书籍
  • C#开发书籍
learn
  • Java编程语言
  • Kotlin 编程入门与实战
  • /python/outline.html
  • AI Agent
  • MCP (Model Context Protocol) 应用指南
  • 深度学习
  • 深度学习
  • 强化学习: 理论与实践
  • 扩散模型书籍
  • Agentic AI for Everyone
langchain
  • 第3章:面向对象编程

第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 接口的高级用法

  1. 函数类型接口:
interface SearchFunc {
  (source: string, keyword: string): boolean;
}

let mySearch: SearchFunc = function(src, kw) {
  return src.indexOf(kw) > -1;
}
  1. 索引类型接口:
interface StringArray {
  [index: number]: string;
}

let arr: StringArray = ["ArkTS", "TypeScript"];
  1. 接口继承:
interface Shape {
  color: string;
}

interface Square extends Shape {
  sideLength: number;
}

3.3.4 接口与类型别名的区别

特性接口(interface)类型别名(type)
扩展方式使用extends继承使用&交叉类型
声明合并支持不支持
实现约束可通过implements不能直接实现
原始类型/联合类型不能定义可以定义

3.3.5 最佳实践

  1. 优先使用接口定义对象形状
  2. 使用readonly约束不应被修改的属性
  3. 通过接口组合实现复杂类型定义
  4. 在组件通信中定义清晰的接口规范

示例:组件通信接口:

// 定义组件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运行时特性进行编译优化。

Last Updated:: 5/22/25, 5:00 PM