将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)
我错过了什么问题,如何有效地重构?
发布于 2020-02-19 12:53:16
这是因为[]
被键入为never[]
。但是,由于您在concat
的第一个例子中调用了Array.prototype
,即any[]
,所以any[]
和(typeof x)[]
之间就会发生连接。
“矩-矩,矩”类型的
论证
所以你想把它正常化给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];
}
https://stackoverflow.com/questions/60299847
复制相似问题