ArkTS Coding Standards
This skill provides guidelines and validation for writing correct ArkTS code, focusing on strict typing and performance optimizations required for HarmonyOS development.
❌ Illegal / Discouraged Practices
The following patterns are forbidden or highly discouraged in ArkTS:
-
Any/Unknown Types:
typescript1let x: any = 1; // ❌ Not allowed: `any` and `unknown` are forbidden. -
Object Literal Types:
typescript1type Inline = { value: number }; // ❌ Don't declare object-literal-based types. -
Fresh Object Literals (Untyped):
typescript1const bad: Inline = { value: 1 }; // ❌ Fresh object literal without declared class/interface instance. -
Runtime Shape Changes:
typescript1bad.newProp = "later"; // ❌ Changing object shape (adding properties) at runtime is forbidden. -
Implicit Object Shapes:
typescript1const obj = { 2 value: 1, 3 double() { 4 return this.value + this.value; // ❌ `this` in a non-method context is disallowed. 5 } 6}; // ❌ Even with an object literal, it must match an explicit class/interface. -
Type Mismatches:
typescript1bad.value = "7"; // ❌ Assigning string to a number-typed field fails. -
Implicit Coercion:
typescript1console.info(String(+bad.value)); // ❌ Unary `+` on a string for coercion is not permitted.
✅ Correct Practices
Use explicit types, classes, and safe conversions:
-
Explicit Numeric Parsing:
typescript1const s: string = "7"; 2// Use explicit parsing methods instead of unary + 3const n: number = Number.parseInt(s); -
Classes and Interfaces: Always define explicit classes or interfaces for your data structures.
typescript1class Doubler { 2 value: number; 3 constructor(value: number) { 4 this.value = value; 5 } 6} 7 8let obj = new Doubler(n);
Summary of Rules
- Static Typing: ArkTS is statically typed. Avoid dynamic features like
any. - Fixed Layout: Object layout is fixed at compile time. You cannot add/remove properties at runtime.
- Explicit Types: Define types explicitly using
classorinterface. Avoid anonymous object types. - Strict Safety: No implicit type coercion. Use standard library functions (e.g.,
Number.parseInt) for conversions.