鸿蒙应用开发实战【86】— 代码质量ArkTS编码规范清单 鸿蒙应用开发实战【86】— 代码质量ArkTS编码规范清单本文是「号码助手全栈开发系列」第 86 篇持续更新中…开源社区https://openharmonycrossplatform.csdn.net前言代码质量是工程化的重要维度。ArkTS 在 TypeScript 基础上增加了严格模式约束strictMode.caseSensitiveCheck等。本篇结合号码助手项目实践整理一份可落地执行的编码规范清单。本篇涵盖命名规范文件/变量/类型、类型安全联合类型 vs enum、异步规范async/await try-catch、组件规范Component Builder、注释规范JSDoc、git 提交规范Angular Commit。一、命名规范类别规范示例文件/目录kebab-caseadd-card-page.ets、sms-parser.ts类/接口PascalCaseclass DatabaseService、interface CardEntity函数/变量camelCasefunction loadData()、let cardId: number类型别名PascalCasetype CardColor ‘blue’常量UPPER_SNAKEconst DB_VERSION 1私有方法camelCaseprivate async doBackup()页面组件Page 后缀struct BackupPage、struct HomePage组件功能命名struct AvatarBadge、struct StatusBadge二、类型安全规范2.1 优先使用联合类型而非 enum// ✅ 推荐exporttypeCardColorblue|orange|green|pink|purpleexporttypeBindingStatus使用中|待换绑|待注销|已停用// ❌ 避免ArkTS 对 enum 支持有限enumCardColor{BLUE,ORANGE,GREEN,PINK,PURPLE}2.2 可选字段明确标记exportinterfaceCardEntity{id?:number// 创建时为 undefined数据库自动分配label:stringphone_number:string// ...}2.3 类型断言用于反序列化category:rs.getString(rs.getColumnIndex(category))asAppCategory,status:rs.getString(rs.getColumnIndex(status))asBindingStatus,三、异步规范3.1 所有 DAO 方法用 async/awaitstaticasyncfindById(id:number):PromiseCardEntity|null3.2 try-catch 三件套try{// 业务逻辑}catch(e){hilog.error(0x0000,TAG,失败: %{public}s,JSON.stringify(e))thrownewError(可读消息: JSON.stringify(e))}3.3 UI 操作放在 finallyfinally{this.loadingfalse// 无论成功失败都结束 loading}四、组件规范Componentexportstruct StatusBadge{Propstatus:string// 输入参数需给默认值build(){// build() 内不应包含复杂逻辑}}规则Prop必须给默认值build()内只放 UI 声明逻辑提取到方法Builder用于复用 UI 片段五、注释规范/** * 号码助手 — RDB 单例 * * 4 张表 * cards 卡号 * app_bindings 应用绑定关系 * sms_candidates 短信/粘贴文本解析出的待确认平台 * sync_meta 云同步元数据 */exportclassDatabaseService{...}六、Git 提交规范type(scope): subject body footerType含义示例feat新功能feat(backup): 实现数据备份与恢复fix修复fix(search): 修复空指针崩溃refactor重构refactor(dao): 统一异常处理docs文档docs: 添加 READMEstyle格式style: 格式化代码小结规范核心要求强制等级命名kebab-case 文件 / PascalCase 类型 / camelCase 变量P0 必须类型联合类型 enum、可选字段 ?、反序列化 as 断言P0 必须异步async/await try-catch finallyP1 重要组件Prop 默认值、build 只放 UIP1 重要注释JSDoc 类级注释、关键方法注释P2 建议GitAngular Commit 规范feat/fix/refactor/docsP1 重要如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力相关资源openHarmony 跨平台社区https://openharmonycrossplatform.csdn.netHarmonyOS 官方文档https://developer.huawei.com/consumer/cn/doc/HarmonyOS hilog文档https://developer.huawei.com/consumer/cn/doc/harmonyos-references/hilogHarmonyOS testinghttps://developer.huawei.com/consumer/cn/doc/harmonyos-guides/unit-testArkTS 编码规范https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-style-guide