arkts-no-props-by-index:禁止通过字符串下标动态访问对象属性

解决 ArkTS 编译报错 Indexed access is not supported for fields (arkts-no-props-by-index),对比 Record、Map 与显式属性访问的标准写法。

规则码
arkts-no-props-by-index
错误码
10605029
级别
error
适用
API 12+ (HarmonyOS NEXT)
更新
2026/12/02

一句话排查结论

访问 class 或 interface 的已知属性时统一使用点号 obj.prop;如果键名在运行时才动态确定,改用 Record<string, ValueType> 或 Map<string, ValueType> 存储数据。

为什么在 ArkTS 中会报这个错

通过 obj[key] 动态访问普通对象字段会绕过编译期静态偏移量优化,并且容易读到 undefined。依据 OpenHarmony 官方规范(错误码 10605029),ArkTS 限制下标访问仅用于数组、TypedArray 和 Record,访问普通类/接口字段必须使用点操作符。

错误写法示例(TypeScript 习惯)

class ThemeColors {
  primary: string = '#1d4ed8';
  danger: string = '#dc2626';
}

const theme = new ThemeColors();
// 错误:对 class 实例使用字符串下标读取属性
const color = theme['primary'];

正确改法(HarmonyOS NEXT 严格模式)

class ThemeColors {
  primary: string = '#1d4ed8';
  danger: string = '#dc2626';
}

const theme = new ThemeColors();
// 正确:已知字段使用点操作符
const primaryColor: string = theme.primary;

// 正确:动态键名场景使用 Record 或 Map
const colorTable: Record<string, string> = {
  'primary': '#1d4ed8',
  'danger': '#dc2626'
};
const dynamicKey: string = 'danger';
const picked: string = colorTable[dynamicKey];

实际开发常见场景与避坑

  1. 国际化多语言词典:词条映射表直接声明为 Record<string, string> 或 Map<string, string>,不要定义为普通 class。
  2. 表单字段动态校验:当需要根据字段名更新表单错误提示时,将错误集合定义为 Map<string, string>,用 errors.set(field, msg) 管理。

常见问题 FAQ

为什么 obj['name'] 会报错,而 Record<string, string> 用 map['name'] 却不报错?▾

普通 class/interface 的字段采用静态偏移量访问,必须使用点语法 obj.name;而 Record<K, V> 本身就是为动态键值映射设计的容器,支持下标访问。

相关推荐阅读