arkts-no-in:ArkTS 禁止使用 in 运算符检查属性

解决 HarmonyOS NEXT 编译报错 'in' operator is not supported (arkts-no-in),详解 instanceof、可选链与 Map.has 的正确替代方案。

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

一句话排查结论

联合类型收窄改用 instanceof 或显式判别字段(如 item.kind === 'video');判断字典是否包含某键改用 Map.has(key) 或 Object.keys(record).includes(key)。

为什么在 ArkTS 中会报这个错

prop in obj 会在运行时沿整个原型链动态查找属性名,在静态强类型对象上既多余又低效。ArkTS 鼓励通过类继承关系(instanceof)或显式标签字段做编译期可验证的类型收窄。

错误写法示例(TypeScript 习惯)

class ImageMsg {
  url: string = '';
}

class TextMsg {
  text: string = '';
}

function renderMsg(msg: ImageMsg | TextMsg): void {
  // 错误:使用 in 运算符做类型守卫
  if ('url' in msg) {
    console.info(msg.url);
  }
}

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

class ImageMsg {
  url: string = '';
}

class TextMsg {
  text: string = '';
}

function renderMsg(msg: ImageMsg | TextMsg): void {
  // 正确:使用 instanceof 进行名义类型收窄
  if (msg instanceof ImageMsg) {
    console.info(msg.url);
  } else {
    console.info(msg.text);
  }
}

实际开发常见场景与避坑

  1. 接口返回 JSON 的多态消息:如果对象来自 JSON.parse()(并非 new ImageMsg() 创建),instanceof 会返回 false,此时应在模型中定义统一的 type: 'image' | 'text' 判别字段。
  2. 检查动态字典键:对于 Record<string, string>,优先使用 Object.keys(headers).includes('token')(或 headers['token'] !== undefined,注意该下标写法仅适用于 Record,对普通 class 会触发 arkts-no-props-by-index);使用 Map 时直接调用 map.has('token')。

常见问题 FAQ

for...in 循环也会受影响吗?▾

是的。ArkTS 同时禁用 for...in(arkts-no-for-in),遍历数组请使用 for...of 或普通下标循环,遍历字典键请使用 Object.keys() 或 Map.keys()。

相关推荐阅读