rules/arkts/coding-style.md
This file extends common/coding-style.md with HarmonyOS and ArkTS-specific content.
ArkTS is a strict, statically-typed subset of TypeScript. Violating these constraints causes compilation failures.
any or unknown types - always use explicit typesinfer keywordtypeof for type annotations - use explicit type declarationsas const assertions - use explicit type annotationsPartial, Required, Readonly, RecordRecord<K, V>, index expression type is V | undefinedcatch clauses (ArkTS does not support any/unknown)async/await for multitaskingFunction.apply, Function.call, Function.bind - follow traditional OOP for thisthis in standalone functions or static methods - only in instance methodsnew.targetlet v!: T) - use initialized declarationsobj["field"] access - use obj.field syntaxdelete operator - use nullable type with null to mark absencein operator - use instanceofSymbol() API (except Symbol.iterator)globalThis or global scope - use explicit module exports/importsrequire() - use regular import syntaxexport = ... - use normal export/importimport statements must appear before all other statementsvar - use letfor...in loops - use regular for loops for arrayswith statements# private identifiers - use private keywordfor loops+, -, ~ only for numeric types (no implicit string conversion)any/Object/object types, classes/interfaces with methods, classes with parameterized constructors, classes with readonly fieldscamelCase (e.g., getUserInfo, goodsList)PascalCase (e.g., UserViewModel, IGoodsModel)UPPER_SNAKE_CASE (e.g., MAX_PAGE_SIZE, COLOR_PRIMARY)PascalCase for components (e.g., HomePage.ets), camelCase for utilitiesvar - prefer const, then let.ets): one @ComponentV2 per file@file (file purpose) + @author (developer), if the project already uses file headers@param, @returns; add @example for complex methods// Use try/catch with proper error handling
try {
const result = await riskyOperation()
return result
} catch (error) {
hilog.error(0x0000, 'TAG', 'Operation failed: %{public}s', error)
throw new Error('User-friendly error message')
}
Follow the common immutability principles - create new objects instead of mutating:
// BAD: mutation
function updateUser(user: UserModel, name: string): UserModel {
user.name = name // direct mutation
return user
}
// GOOD: immutable - create new instance
function updateUser(user: UserModel, name: string): UserModel {
const updated = new UserModel()
updated.id = user.id
updated.name = name
updated.email = user.email
return updated
}