将 Array.prototype.concat.apply([], [x])
重构为 [].concat(x)
会引发此错误:
No overload matches this call.
Overload 1 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
Argument of type 'Moment | [Moment, Moment]' is not assignable to parameter of type 'ConcatArray<never>'.
Type 'Moment' is missing the following properties from type 'ConcatArray<never>': length, join, slice
Overload 2 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
Argument of type 'Moment | [Moment, Moment]' is not assignable to parameter of type 'ConcatArray<never>'.
Type 'Moment' is not assignable to type 'ConcatArray<never>'.ts(2769)
我遗漏了什么问题以及如何有效地重构它?
最佳答案
这是因为 []
的类型为 never[]
。但由于您在 Array.prototype
的第一个示例中调用 concat
(即 any[]
),因此串联发生在 any[] 之间
和 (typeof x)[]
Argument of type 'Moment | [Moment, Moment]'
所以你想将其标准化为Moment[]
?
你可以这样做:
let y:Moment[];
y = ([] as any[]).concat(x);
// or something like
y = "length" in x ? x: [x];
// or something completely different, as you are already refactoring.
const [
from = x,
to = x
] = x as any;
或者将其放入函数中
function foo<T>(arg: T|T[]): T[] {
return Array.isArray(arg) ? arg : [arg];
}
关于javascript - 将 Array.prototype.concat.apply([], [x]) 重构为 [].concat(x) 会引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60299847/