利用 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 # 查看幫助信息