arrays - 使用 TypeScript 将数组传递给扩展运算符参数

标签 arrays typescript

我有一个继承自 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/

相关文章:

typescript - 如何在 TypeScript 中为可索引类型的键创建字符串文字类型?

class - TypeScript - 将类存储为 map 值?

typescript - 检查泛型元组是否扩展括号中的表达式有何作用?

arrays - 二维数组的唯一编号分配

PHP 迭代器不能通过引用与 foreach 一起使用

arrays - Swift 设置为数组

javascript - 类型 'string | ArrayBuffer' 不可分配给类型 'string'

python - NumPy boolean 数组警告?

c# - 将 MySql 不同的值传递到 c# 字符串中

Angular 4 服务方法总是返回未定义而不是 Observable