Date:

鸿蒙Next Ark TS 语法适配背景概述

一、引言

ArkTS在保持TypeScript(TS)基本语法风格的基础上,通过规范强化静态检查和分析,在程序开发期检测更多错误,提升程序稳定性与运行性能。本文将阐述为何建议将TS代码适配为ArkTS代码。

二、程序稳定性

(一)动态类型语言的问题

以JavaScript(JS)为代表的动态类型语言,虽能让开发者快速编写代码,但容易在运行时产生非预期错误。如未检查值是否为undefined,可能导致程序崩溃。

(二)TypeScript的局限性

TS通过标注类型检查错误,多数错误在编译时可被检测,但不强制变量类型标注,限制了编译时检查。

(三)ArkTS的改进

ArkTS强制使用静态类型,要求类的属性在声明或构造函数中显式初始化,减少运行时错误。例如:

  1. TS非严格模式下的类定义(存在问题)
class Person {
    name: string; // undefined
    setName(n: string): void {
        this.name = n;
    }
    getName(): string {
        return this.name;
    }
}
let buddy = new Person();
buddy.getName().length; // 运行时异常: name is undefined
  1. ArkTS改进后的类定义(更安全)
class Person {
    name: string = '';
    setName(n: string): void {
        this.name = n;
    }
    getName(): string {
        return this.name;
    }
}
let buddy = new Person();
buddy.getName().length; // 0, 没有运行时异常

三、程序性能

(一)动态类型语言的运行时检查

动态类型语言为保证正确性,在运行时检查对象类型,如JS访问undefined属性时会检查类型,这虽可优化但仍影响性能。TS编译成JS后也有同样问题。

(二)ArkTS的解决方案

ArkTS使能静态类型检查,编译成方舟字节码文件而非JS代码,运行速度更快且更易优化。

(三)Null Safety特性

  1. 示例函数及问题
function notify(who: string, what: string) {
    console.log(`Dear ${who}, a message for you: ${what}`);
}
notify('Jack', 'You look great today');
notify(null, undefined); // 程序仍运行,但引擎做了额外类型检查
  1. ArkTS的严格检查

ArkTS强制严格null检查,保证null不是合法string类型变量的值,不符合类型的代码无法编译,有助于优化性能。如上述notify(null, undefined)在ArkTS中会编译报错。

四、.ets代码兼容性

(一)语法规则变化

API version 10之前,ArkTS(.ets文件)采用标准TS语法。从API version 10 Release起,ArkTS语法规则明确定义,SDK增加编译时语法检查。

<h3

Latest stories

Read More

Opinion: Exotec managing director highlights key warehouse automation trends for 2026

Thomas Genestar, managing director of western Europe at...

MassRobotics opens RoboBoston 2026 sponsorships and announces AI career fair

MassRobotics has announced that it will host RoboBoston...

Agility Robotics opens new Fremont facility to accelerate physical AI development

Agility Robotics, a humanoid robotics and physical AI...

Luyten opens early reservations for Ascend A27 automated construction platform

Australian construction robotics company Luyten has opened early...

LEAVE A REPLY

Please enter your comment!
Please enter your name here