一、数组字面量必须仅包含可推断类型的元素
规则:arkts-no-noninferrable-arr-literals
级别:错误
本质上,ArkTS将数组字面量的类型推断为数组所有元素的联合类型。如果其中任何一个元素的类型无法根据上下文推导出来(例如,无类型的对象字面量),则会发生编译时错误。
TypeScript

let a = [{n: 1, s: '1'}, {n: 2, s: '2'}];
  • 1.

ArkTS

class C {
  n: number = 0
  s: string = ''
}

let a1 = [{n: 1, s: '1'} as C, {n: 2, s: '2'} as C]; // a1的类型为“C[]”
let a2: C[] = [{n: 1, s: '1'}, {n: 2, s: '2'}];    // a2的类型为“C[]”
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

相关约束
对象字面量必须对应某些显式声明的类或接口
对象字面量不能用于类型声明
二、使用箭头函数而非函数表达式
规则:arkts-no-func-expressions
级别:错误
ArkTS不支持函数表达式,使用箭头函数。
TypeScript

let f = function (s: string) {
  console.log(s);
}
  • 1.
  • 2.
  • 3.

ArkTS

let f = (s: string) => {
  console.log(s);
}
  • 1.
  • 2.
  • 3.

不支持使用类表达式
规则:arkts-no-class-literals
级别:错误
ArkTS不支持使用类表达式,必须显式声明一个类。
TypeScript

const Rectangle = class {
  constructor(height: number, width: number) {
    this.height = height;
    this.width = width;
  }

  height
  width
}

const rectangle = new Rectangle(0.0, 0.0);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

ArkTS

class Rectangle {
  constructor(height: number, width: number) {
    this.height = height;
    this.width = width;
  }

  height: number
  width: number
}

const rectangle = new Rectangle(0.0, 0.0);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

三、类不允许implements
规则:arkts-implements-only-iface
级别:错误
ArkTS不允许类被implements,只有接口可以被implements。
TypeScript

class C {
  foo() {}
}

class C1 implements C {
  foo() {}
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

ArkTS

interface C {
  foo(): void
}

class C1 implements C {
  foo() {}
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

本文根据HarmonyOS NEXT Developer Beta1官方公开的开发文档整理而成。