首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将Array.prototype.concat.apply([],[x])重构为[].concat(x)引发错误

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

Stack Overflow用户
提问于 2020-02-19 11:57:07
回答 1查看 329关注 0票数 0

Array.prototype.concat.apply([], [x])重构为[].concat(x)会引发以下错误:

代码语言:javascript
运行
复制
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) 

我错过了什么问题,如何有效地重构?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-02-19 12:53:16

这是因为[]被键入为never[]。但是,由于您在concat的第一个例子中调用了Array.prototype,即any[],所以any[](typeof x)[]之间就会发生连接。

“矩-矩,矩”类型的

论证

所以你想把它正常化给Moment[]吗?你可以:

代码语言:javascript
运行
复制
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;

或者你把它放到一个函数里

代码语言:javascript
运行
复制
function foo<T>(arg: T|T[]): T[] {
  return Array.isArray(arg) ? arg : [arg];
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60299847

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档