赞
踩
由于业务需求更新的API前段时间写的APP需要更新到API10,记录在修改过程中发现的一系列问题
"for .. in" is not supported (arkts-no-for-in) <ArkTSCheck>
for .. in
规则:arkts-no-for-in
级别:错误
由于在ArkTS中,对象布局在编译时是确定的、并且不能在运行时被改变,所以不支持使用for .. in
迭代一个对象的属性。对于数组来说,可以使用常规的for
循环。
- interface Person {
- [name: string]: string
- }
- let p: Person = {
- name: 'tom',
- age: '18'
- };
-
- for (let t in p) {
- console.log(p[t]);
- }
- typescript
- let p: Record<string, string> = {
- 'name': 'tom',
- 'age': '18'
- };
-
- for (let ele of Object.entries(p)) {
- console.log(ele[1]);
- }
规则:arkts-no-props-by-index
级别:错误
ArkTS不支持动态声明字段,不支持动态访问字段。只能访问已在类中声明或者继承可见的字段,访问其他字段将会造成编译时错误。 使用点操作符访问字段,例如(obj.field
),不支持索引访问(obj[field]
)。 ArkTS支持通过索引访问TypedArray
(例如Int32Array
)中的元素。
可以转换成Record类型,用来访问对象的属性。
- import myRouter from '@ohos.router';
- let params: Object = myRouter.getParams();
- let funNum: number = params['funNum'];
- let target: string = params['target'];
- typescript
- import myRouter from '@ohos.router';
- let params = myRouter.getParams() as Record<string, string | number>;
- let funNum: number = params.funNum as number;
- let target: string = params.target as string;
规则:arkts-no-inferred-generic-params
级别:错误
如果可以从传递给泛型函数的参数中推断出具体类型,ArkTS允许省略泛型类型实参。否则,省略泛型类型实参会发生编译时错误。 禁止仅基于泛型函数返回类型推断泛型类型参数。
- class A {
- str: string = ''
- }
- class B extends A {}
- class C extends A {}
-
- let arr: Array<A> = [];
-
- let originMenusMap:Map<string, C> = new Map(arr.map(item => [item.str, (item instanceof C) ? item: null]));
- typescript
- class A {
- str: string = ''
- }
- class B extends A {}
- class C extends A {}
-
- let arr: Array<A> = [];
-
- let originMenusMap: Map<string, C | null> = new Map<string, C | null>(arr.map<[string, C | null]>(item => [item.str, (item instanceof C) ? item: null]));
- typescript
(item instanceof C) ? item: null
需要声明类型为C | null
,由于编译器无法推导出map
的泛型类型参数,需要显式标注。
规则:arkts-identifiers-as-prop-names
级别:错误
在ArkTS中,对象的属性名不能为数字或字符串。通过属性名访问类的属性,通过数值索引访问数组元素。
- interface W {
- bundleName: string
- action: string
- entities: string[]
- }
-
- let wantInfo: W = {
- 'bundleName': 'com.huawei.hmos.browser',
- 'action': 'ohos.want.action.viewData',
- 'entities': ['entity.system.browsable']
- }
- typescript
- interface W {
- bundleName: string
- action: string
- entities: string[]
- }
-
- let wantInfo: W = {
- bundleName: 'com.huawei.hmos.browser',
- action: 'ohos.want.action.viewData',
- entities: ['entity.system.browsable']
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。