我想创建一个类似数组的类并向其添加一些属性。到目前为止我有这个代码:
class MyArray<T> extends Array<T> {
constructor(items: T[], data?: any) {
super(...items)
this.#data = data
}
#data: any
public get data() {
return this.#data
}
}
但是此代码失败并显示错误“Spread 语法需要 ...iterable[Symbol.iterator] 为函数”:
const myArray = new MyArray([1, 2, 3], {})
console.log(myArray)
我猜我的构造函数有问题。有人能指出我正确的方向吗? 看TS游乐场
您遇到的错误是因为 Array 构造函数需要可迭代的参数,而 MyArray 无法在构造函数中正确处理项目的传播。这是代码的更正版本:
class MyArray<T> extends Array<T> {
constructor(items: T[], data?: any) {
// If data is provided, spread items inside super call; otherwise, pass empty array
super(data ? ...items : undefined);
this.#data = data;
}
#data: any;
public get data() {
return this.#data;
}
}
说明:
在构造函数中,如果提供了数据,则使用扩展运算符...来扩展项目数组。如果未提供数据,则会将空数组传递给 super 调用。 这确保超级调用按预期接收可迭代参数。 使用此更正后的代码,您的示例应该按预期工作:
const myArray = new MyArray([1, 2, 3], {});
console.log(myArray); // Output: MyArray [ 1, 2, 3 ]
console.log(myArray.data); // Output: {}
让我们修改代码来处理未提供数据的情况:
class MyArray<T> extends Array<T> {
#data: any;
constructor(items: T[], data?: any) {
// If data is provided, pass items to super(); otherwise, pass no arguments
super(...(data ? items : []));
this.#data = data;
}
public get data() {
return this.#data;
}
}
在此修订版中:
如果提供了数据,项目将在 super() 调用中传播。 如果未提供数据,则将空数组 [] 传递给 super()。