arrays - [首先,...休息] : A spread argument must either have a tuple type or be passed to a rest parameter. ts(2556)

标签 arrays typescript constructor apply

设置

class X {
    constructor(first: string, ...rest: string[]) { }
}

new X(...["foo", "bar"])

产生错误

A spread argument must either have a tuple type or be passed to a rest parameter.ts(2556)

这正在工作:

new X("foo", ...["bar"])

但这不是很方便。

如果我使用

class X {
    constructor(...all: string[]) { }
}

相反,它工作正常,所以它一定与我分成 firstrest 有关。但是有没有办法让这个工作与分割参数一起工作?

最佳答案

["foo", "bar"] 的类型是 string[]。如果您无法使用 as const 控制 this 的类型,因为您在其他地方获得了它,则可以验证并缩小类型,例如:

const input:string[] = ["foo", "bar"];

if (!input.length<1) {
  throw new Error('Input must at least have 1 element');
}
const tuple: [string, ...string[]] = [input[0], ...input.slice(1)];
}

如果作业感觉很傻,我觉得这样更优雅:

const input:string[] = ["foo", "bar"];

function assertAtLeast1Element(input: string[]): asserts input is [string, ...string[]] {
  if (input.length < 1) throw new Error('Input must at least have 1 element');
}

assertAtLeast1Element(input);

class X {
    constructor(first: string, ...rest: string[]) { }
}

new X(...input);

关于arrays - [首先,...休息] : A spread argument must either have a tuple type or be passed to a rest parameter. ts(2556),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75046014/

相关文章:

javascript - 在排序数组中查找/跟踪元素

javascript - 查找行数组中最后一列的最后一个值

java - 在java中构造一个类,向两个单独的面板gui、驱动程序类和主类添加标签

java - 用于查找整数的二进制和线性搜索程序。如果存在则回答 yes,如果不存在则回答 no。如何让二分查找工作?

typescript 通用特化

reactjs - 不可变的 JS 列表大小

javascript - 未找到服务中的 Angular 7 类

c++ - 安全放置新的和显式的析构函数调用

javascript - 为什么 JavaScript ES6 不支持多构造类?

java - android 数组通过可绘制资源与 onClick 事件