我有一个继承自 Array 的类:
class List<T> extends Array<T> {
constructor(items: T[]) {
super(items); // error here...
}
}
Argument of type 'T[]' is not assignable to parameter of type 'T'.
假设这是因为 Array 的构造函数采用 (...items: T[])
那么,如何将标准数组传递给需要扩展运算符的对象?
最佳答案
Array Constructor 接受任意数量的参数。如果您将一个数组传递给 new Array()
,它会被分配给第一个索引。
const newArray = new Array([1, 2, 3]);
console.log(newArray); // [[1, 2, 3]];
使用扩展运算符将数组展开为参数。
const newArray = new Array(...[1, 2, 3]); // equivalent to new Array(1, 2, 3);
console.log(newArray); // [1, 2, 3];
所以你的类看起来像这样:
class List<T> extends Array<T> {
constructor(items: T[]) {
super(...items); // Spread operator here
}
}
关于arrays - 使用 TypeScript 将数组传递给扩展运算符参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41556313/