arkts-no-obj-literals-as-types:禁止使用对象字面量作为类型声明

解析 ArkTS 编译错误 Object literals cannot be used as type declarations (arkts-no-obj-literals-as-types),提供内联对象类型改为具名 interface 与 class 的重构方法。

规则码
arkts-no-obj-literals-as-types
错误码
10605040
级别
error
适用
API 12+ (HarmonyOS NEXT)
更新
2026/12/02

一句话排查结论

把所有写在变量注解、函数参数、返回值或 type 别名里的内联对象类型 { key: Type } 提取成独立的具名 interface 或 class。

为什么在 ArkTS 中会报这个错

ArkTS 采用名义类型系统(Nominal Typing)而非 TypeScript 的结构类型系统。匿名内联对象类型 { x: number; y: number } 没有具名符号,无法在不同模块之间建立稳定的类型身份,因此被 arkts-no-obj-literals-as-types 禁止。

错误写法示例(TypeScript 习惯)

// 错误:函数参数和返回值直接使用对象字面量作为类型
function formatUser(user: { id: number; name: string }): { label: string } {
  return { label: `${user.id}-${user.name}` };
}

// 错误:type 别名右值为对象字面量
type Size = { width: number; height: number };

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

// 正确:将所有结构提取为具名 interface 或 class
interface UserBrief {
  id: number;
  name: string;
}

interface FormattedLabel {
  label: string;
}

interface Size {
  width: number;
  height: number;
}

function formatUser(user: UserBrief): FormattedLabel {
  return { label: `${user.id}-${user.name}` };
}

实际开发常见场景与避坑

  1. Promise 返回值类型:Promise<{ code: number; msg: string }> 是最高频的踩坑点,务必提取为 interface BaseResp 后写成 Promise<BaseResp>。
  2. 嵌套类字段:在 class Order 中不要写 address: { city: string; street: string },应拆出 export class Address。
  3. 组件 @Prop / @Param 类型:ArkUI 自定义组件的参数类型同样不允许内联对象字面量,统一定义在独立的 model/ 文件中导出。

常见问题 FAQ

type Point = { x: number; y: number } 也会触发这个报错吗?▾

会的。在 ArkTS 中,使用 type 定义内联对象字面量类型同样被禁止,必须改用 interface Point { ... } 或 class Point { ... }。

嵌套对象类型怎么拆分最省事?▾

每一层嵌套对象都单独提取为具名的 interface 或 export class。可以直接用本站的 JSON 转 ArkTS Class 工具自动完成多层嵌套拆分。

相关推荐阅读