本文同步发表于我的微信公众号,微信搜索 程语新视界 即可关注,每个工作日都有文章更新

在鸿蒙开发中,interfacetype 都是用来定义类型的关键字,但它们有重要的区别。详细对比如下:

一、核心区别总结

特性interfacetype
扩展性可通过 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 的场景:

  1. 需要声明合并(如扩展第三方库类型)
  2. 需要被类 implements 实现
  3. 定义对象类型且需要清晰的可读性
  4. 鸿蒙UI组件Props/State定义

优先使用 type 的场景:

  1. 需要定义联合类型、元组类型
   type ID = string | number;
   type Coord = [number, number];

    2. 需要定义函数类型

   type ClickHandler = (event: Event) => void;

五、开发建议

  1. 项目规范

    • 统一团队约定(如对象类型用interface,工具类型用type)
    • .eslintrc中配置首选类型规则
  2. 性能考量

    • 大型项目中使用interface可能获得更好的类型检查性能
    • 复杂类型推导使用type更灵活
  3. 联合类型实践

   // 定义鸿蒙组件状态
   type ComponentState = 
     | { status: 'loading' }
     | { status: 'success', data: Item[] }
     | { status: 'error', error: Error };

其实开发中,两者大部分情况下可以互换,关键是根据团队规范和具体场景选择最合适的工具。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐