arkts-no-spread:ArkTS 展开运算符使用限制与对象合并替代方案
解决 HarmonyOS NEXT 报错 It is possible to spread only arrays or classes derived from arrays into the rest parameter or array literals (arkts-no-spread),详解对象浅拷贝替代写法。
- 规则码
- arkts-no-spread
- 错误码
- 10605099
- 级别
- error
- 适用
- API 12+ (HarmonyOS NEXT)
- 更新
- 2026/12/02
一句话排查结论
数组展开 [...a, ...b] 可继续使用,但禁止使用对象展开 { ...obj };需要复制或合并对象时,请显式构造新实例、编写 clone() 方法,或使用 @ObservedV2 直接原地修改属性。
为什么在 ArkTS 中会报这个错
依据 OpenHarmony 官方规范(错误码 10605099),ArkTS 仅支持使用展开运算符展开数组、Array 的子类以及 TypedArray(例如 Int32Array),且仅限于数组字面量或传递给剩余参数。对象展开 { ...a, ...b } 需要在运行时动态枚举源对象属性并构造匿名对象,违反静态布局原则,因此被严格模式禁止。
错误写法示例(TypeScript 习惯)
class UserProfile {
name: string = '';
age: number = 0;
}
const origin = new UserProfile();
origin.name = '张三';
origin.age = 26;
// 错误:对象展开运算符不被支持
const updated: UserProfile = { ...origin, age: 27 };
正确改法(HarmonyOS NEXT 严格模式)
class UserProfile {
name: string = '';
age: number = 0;
// 正确:提供显式拷贝或构造逻辑
cloneWithAge(newAge: number): UserProfile {
const next = new UserProfile();
next.name = this.name;
next.age = newAge;
return next;
}
}
const origin = new UserProfile();
origin.name = '张三';
origin.age = 26;
const updated: UserProfile = origin.cloneWithAge(27);
// 数组展开是合法的
const partA: number[] = [1, 2];
const partB: number[] = [3, 4];
const merged: number[] = [...partA, ...partB];
实际开发常见场景与避坑
- 禁止将数组展开传递给普通固定形参:例如
function sum(a: number, b: number)不能用sum(...[1, 2])调用;数组展开仅允许用于数组字面量[...a, ...b]或传递给剩余参数(...rest: number[])。 - 慎用
Object.assign:虽然部分迁移场景下可以使用Object.assign,但不如显式字段赋值或自定义clone()方法具备完整的静态类型安全。 - 配合
@ComponentV2:在 V2 状态管理中,直接修改@Trace修饰的字段即可触发局部刷新,彻底告别前端不可变对象展开写法。
常见问题 FAQ
ArkTS 里完全不能用 ... 展开运算符吗?▾
不是完全禁止。数组展开到数组字面量或剩余参数(如 [...arr1, ...arr2])是允许的;但对象展开({ ...obj1, ...obj2 })在严格模式下是被禁止的。
在 ArkUI 状态更新中不能用 { ...this.user, name: '新名字' },该怎么触发刷新?▾
如果使用 API 12+ 的 @ObservedV2 和 @Trace,直接修改 this.user.name = '新名字' 即可精准刷新,无需创建新对象拷贝;若需拷贝对象,可编写类的 clone() 方法。
开发者资源