利用 i2c 快速从 Interface 生成 Class

发布于:2025-04-20 ⋅ 阅读:(92) ⋅ 点赞:(0)

利用 i2c 快速从 Interface 生成 Class(支持 TS & ArkTS)

在日常 TypeScript 或 ArkTS 开发中,需要根据 interface 定义手动实现对应的 class,这既重复又容易出错。分享一个命令行工具 —— interface2class,简称 i2c,可以自动完成class生产。


🔧 工具简介

  • 名称interface2class(i2c)
  • 作用:根据 .ts.ets 文件中的 interface 自动生成对应的 class 实现
  • 适用语言:TypeScript、ArkTS
  • 项目地址:https://github.com/HarmonyOS-Next/interface2class

📦 安装方式

推荐使用全局安装:

npm install -g interface2class

⚙️ 使用示例

假设有一个 ArkTS 的接口文件 message.ets,内容如下:

export interface Message {
  id: number;
  title: string;
  content: string;
  send(): void;
}

运行以下命令:

i2c ./message.ets

即可自动生成一个 message.ts 文件,内容如下:

export class MessageImpl implements Message {
  id: number;
  title: string;
  content: string;

  constructor() {
    this.id = 0;
    this.title = '';
    this.content = '';
  }

  send(): void {
    throw new Error("Method not implemented.");
  }
}

非常适合快速搭建原型、数据模型、Mock 类等。


❗ 遇到的问题:EPERM 权限错误

在安装时,我遇到了如下报错:

npm ERR! code EPERM
npm ERR! syscall mkdir
npm ERR! path D:\chang\dev_tools\DevEco Studio\tools\node\node_modules\interface2class
npm ERR! errno -4048
npm ERR! Error: EPERM: operation not permitted, mkdir ...

🛠️ 原因分析

这是 Windows 系统下常见的 权限不足 问题,主要原因可能包括:

  • DevEco Studio 自带 Node 环境为受限目录,无法写入
  • 当前终端未以管理员权限运行
  • 系统安全软件(如杀毒软件)拦截

✅ 解决方法

采用了以下方案成功解决:

DevEco Studio 安装目录中 node_modules 设置为“可修改”权限。

或者也可以选择:

  • 右键 PowerShell / CMD → 以管理员身份运行

  • 或者使用自己系统安装的 Node(非 DevEco 内置),例如:

    npm install -g interface2class
    

📝 总结

优点 说明
🚀 快速 从 interface 一键生成 class,省时省力
🔁 自动化 无需重复写构造函数、属性定义
🧱 项目友好 支持 TS 与 ArkTS,适合 HarmonyOS 生态

如果你也在做多模型 ArkTS 项目,或正在用 HarmonyOS 的 DevEco Studio,不妨尝试这个工具。


附上命令验证小技巧:

i2c -v   # 查看版本号
i2c      # 查看帮助信息

网站公告

今日签到

点亮在社区的每一天
去签到