javascript - 将 Array.prototype.concat.apply([], [x]) 重构为 [].concat(x) 会引发错误

标签 javascript typescript

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/

相关文章:

javascript - 如何在 Javascript 中显示 2^3

typescript - 如何表示不可变对象(immutable对象)的不可变数组?

javascript - 正确的 ES6 导入以添加力矩精确范围插件

javascript - 将英国夏令时间日期更改为 GMT 日期

javascript - 通过电子邮件发送函数返回的值

javascript - Sequelize.js,模型的最大 pubDate 返回旧条目而不是最新条目

javascript - Cordova 套接字编程

javascript - 鼠标离开输入时显示错误

visual-studio - Visual Studio 2012 中的 TypeScript 未编译

javascript - ASP.NET重构思路: TypeScript