HarmonyOS鸿蒙Next中Record<string, string>常量要怎么声明?

HarmonyOS鸿蒙Next中Record<string, string>常量要怎么声明?

const loginParams: Record<string, string> = {
  model: 'ohos',
  serial: 'ohos-im-http-test-12345'
}

这就是需要声明一个键值对常量, 类似其他语言的map,ts没问题,但arkts就死活不让赋值,

Object literal must correspond to some explicitly declared class or interface (arkts-no-untyped-obj-literals) <ArkTSCheck>

把内容删了倒是能编译通过,有些不解,


更多关于HarmonyOS鸿蒙Next中Record<string, string>常量要怎么声明?的实战教程也可以访问 https://www.itying.com/category-93-b0.html

6 回复
const loginParams: Record<string, string> = {
  'model': 'ohos',
  'serial': 'ohos-im-http-test-12345'
}

key应该也是string格式才行

更多关于HarmonyOS鸿蒙Next中Record<string, string>常量要怎么声明?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


你的key类型是string,如下就不会报错了

const loginParams: Record<string, string> = {
  'model': 'ohos',
  'serial': 'ohos-im-http-test-12345'
}

找HarmonyOS工作还需要会Flutter技术的哦,有需要Flutter教程的可以学学大地老师的教程,很不错,B站免费学的哦:BV1S4411E7LY/?p=17

大概能理解arkts要求字面量有个明确的类型,

但这类型必须是每个字段都写明的class吗?

有没有类似record类似其他语言的map的方案,就key value都是字符串可以添加删除的类型,的字面量,

在HarmonyOS Next中,使用TypeScript声明Record<string, string>常量的标准语法如下:

const myRecord: Record<string, string> = {
  "key1": "value1",
  "key2": "value2"
};

若使用ArkTS声明:

const myRecord: Record<string, string> = {
  "key1": "value1",
  "key2": "value2"
} as const;

在HarmonyOS Next的ArkTS中,声明Record<string, string>类型的常量需要使用更严格的类型定义方式。ArkTS对类型检查更为严格,不能直接使用未明确类型的对象字面量。

正确的声明方式有以下两种:

  1. 使用接口明确定义类型:
interface StringMap {
  [key: string]: string;
}

const loginParams: StringMap = {
  model: 'ohos',
  serial: 'ohos-im-http-test-12345'
};
  1. 或者使用Record类型但需要显式类型断言:
const loginParams = {
  model: 'ohos',
  serial: 'ohos-im-http-test-12345'
} as Record<string, string>;

ArkTS要求所有对象字面量必须对应某个显式声明的类或接口,这是为了确保类型安全。空对象{}能通过是因为它不违反这个规则,但当包含属性时就必须提供明确的类型定义。

回到顶部