Why Adapt TS Code to ArkTS Code
Program Stability
Dynamic - typed languages like JavaScript allow developers to write code quickly but can lead to unexpected runtime errors. TypeScript helps catch errors during compilation, but it doesn't enforce type annotations. ArkTS addresses this by mandating static types, enhancing type checking to reduce runtime errors.
For example, in non - strict TS mode:
class Person {
name: string; // undefined
setName(n: string): void {
this.name = n;
}
getName(): string {
return this.name;
}
}
let buddy = new Person();
buddy.getName().length; // Runtime error: name is undefined
ArkTS requires explicit property initialization:
class Person {
name: string = '';
setName(n: string): void {
this.name = n;
}
getName(): string {
return this.name;
}
}
let buddy = new Person();
buddy.getName().length; // Safe, returns 0
If a property can be undefined, its type should be explicitly declared:
class Person {
name?: string; // Can be undefined
setName(n: string): void {
this.name = n;
}
getName(): string | undefined {
return this.name;
}
}
let buddy = new Person();
buddy.getName()?.length; // Safe with optional chaining
Program Performance
Dynamic - typed languages require runtime type checks, which can slow down programs. ArkTS, with static type checking, compiles to Ark byte็ for better performance.
For instance, consider a function in JavaScript:
function notify(who: string, what: string) {
console.log(`Dear ${who}, a message for you: ${what}`);
}
notify('Jack', 'You look great today');
If special values like null
or undefined
are passed, the engine still handles them but with runtime checks. ArkTS ensures such checks are done at compile - time, leading to faster execution.
Null Safety
ArkTS enforces null safety, preventing unexpected null or undefined values. This is similar to TypeScript's strictNullChecks option but is implemented more strictly. In ArkTS, code that could result in null or undefined values won't compile, ensuring safer runtime behavior.
For example:
function notify(who: string, what: string) {
console.log(`Dear ${who}, a message for you: ${what}`);
}
notify(null, undefined); // Compile - time error in ArkTS
.ets Code Compatibility
Before API version 10, ArkTS used standard TypeScript syntax. Starting from API version 10, ArkTS introduced specific syntax rules. The SDK checks .ets files during compilation, prompting developers to adapt to ArkTS syntax.
Interaction with TS/JS
ArkTS supports efficient interoperability with TS/JS. However, in some cases, this interaction might bypass ArkTS's static checks, potentially causing unexpected behavior.
Example:
// lib.ts
export class C {
v: string;
}
export let c = new C();
// app.ets
import { C, c } from './lib';
function foo(c: C) {
c.v.length;
}
Top comments (0)