HarmonyOS 鸿蒙Next中的Record类型

发布于 1周前 作者 itying888 最后一次编辑是 5天前 来自 分享

HarmonyOS 鸿蒙Next中的Record类型

HarmonyOS 鸿蒙Next中Record是TypeScript中的一个高级类型,用于创建一个具有固定键类型和值类型的对象类型。这种类型在HarmonyOS Next的开发中非常有用,因为它可以确保对象属性的键和值都符合特定的类型要求,从而增强类型安全。

应用代码

function printProperties(obj: any) {
  console.log(obj.name);
  console.log(obj.value);
}

建议改法

function printProperties(obj: Record<string, Object>) {
  console.log(obj.name as string);
  console.log(obj.value as string);
}

应用代码

class A {
  v: number = 0
  s: string = ''
  
  foo(str: string) {
    let tmpStr = JSON.parse(str);
    if (tmpStr.add != undefined) {
      this.v = tmpStr.v;
      this.s = tmpStr.s;
    }
  }
}

建议改法

class A {
  v: number = 0
  s: string = ''
  
  foo(str: string) {
    let tmpStr: Record<string, Object> = JSON.parse(str);
    if (tmpStr.add != undefined) {
      this.v = tmpStr.v as number;
      this.s = tmpStr.s as string;
    }
  }
}

应用代码


import { router } from '@kit.ArkUI';
let params: Object = router.getParams();
let funNum: number = params['funNum'];
let target: string = params['target'];

建议改法

import { router } from '@kit.ArkUI';
let params = router.getParams() as Record<string, string | number>;
let funNum: number = params.funNum as number;
let target: string = params.target as string;
回到顶部