HarmonyOS Next原生应用开发-从TS到ArkTS的适配规则(十一)

一、不支持修改对象的方法
规则:arkts-no-method-reassignment
级别:错误
ArkTS不支持修改对象的方法。在静态语言中,对象的布局是确定的。一个类的所有对象实例享有同一个方法。
如果需要为某个特定的对象增加方法,可以封装函数或者使用继承的机制。
TypeScript

class C {
  foo() {
    console.log('foo');
  }
}

function bar() {
  console.log('bar');
}

let c1 = new C();
let c2 = new C();
c2.foo = bar;

c1.foo(); // foo
c2.foo(); // bar

ArkTS

class C {
  foo() {
    console.log('foo');
  }
}

class Derived extends C {
  foo() {
    console.log('Extra');
    super.foo();
  }
}

function bar() {
  console.log('bar');
}

let c1 = new C();
let c2 = new C();
c1.foo(); // foo
c2.foo(); // foo

let c3 = new Derived();
c3.foo(); // Extra foo

二、类型转换仅支持as T语法
规则:arkts-as-casts
级别:错误
在ArkTS中,as关键字是类型转换的唯一语法,错误的类型转换会导致编译时错误或者运行时抛出ClassCastException异常。ArkTS不支持使用<type>语法进行类型转换。
当需要将primitive类型(如number或boolean)转换成引用类型时,请使用new表达式。
TypeScript

class Shape {}
class Circle extends Shape { x: number = 5 }
class Square extends Shape { y: string = 'a' }

function createShape(): Shape {
  return new Circle();
}

let c1 = <Circle> createShape();

let c2 = createShape() as Circle;

// 如果转换错误,不会产生编译时或运行时报错
let c3 = createShape() as Square;
console.log(c3.y); // undefined

// 在TS中,由于`as`关键字不会在运行时生效,所以`instanceof`的左操作数不会在运行时被装箱成引用类型
let e1 = (5.0 as Number) instanceof Number; // false

// 创建Number对象,获得预期结果:
let e2 = (new Number(5.0)) instanceof Number; // true

ArkTS

class Shape {}
class Circle extends Shape { x: number = 5 }
class Square extends Shape { y: string = 'a' }

function createShape(): Shape {
  return new Circle();
}

let c2 = createShape() as Circle;

// 运行时抛出ClassCastException异常:
let c3 = createShape() as Square;

// 创建Number对象,获得预期结果:
let e2 = (new Number(5.0)) instanceof Number; // true

三、不支持JSX表达式
规则:arkts-no-jsx
级别:错误
不支持使用JSX。

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

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值