设置
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[]) { }
}
相反,它工作正常,所以它一定与我分成 first
和 rest
有关。但是有没有办法让这个工作与分割参数一起工作?
最佳答案
["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/