Microsoft/TypeScript

Array concat has wrong types

Open

#47,351 建立於 2022年1月8日

在 GitHub 查看
 (10 留言) (0 反應) (0 負責人)TypeScript (6,726 fork)batch import
BugDomain: lib.d.tsHelp Wanted

倉庫指標

Star
 (48,455 star)
PR 合併指標
 (平均合併 6天 17小時) (30 天內合併 9 個 PR)

描述

Bug Report

A not-uncommon JS idiom is [].concat(x || [], y || [], z || []) as a faster, simpler, more backwards-compatible [x, y, z].flatMap(x => x || []). However, when I try, I get type errors.

🔎 Search Terms

array concat concat overload

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about array concat

⏯ Playground Link

Playground link with relevant code

💻 Code

const a = [].concat(
    true ? 'a' : [],
    false ? 'b' : [],
);

const x = [].concat(
    false ? 'b' : [],
    true ? 'a' : [],
);

🙁 Actual behavior

No overload matches this call.
  Overload 1 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
    Argument of type 'never[] | "a"' is not assignable to parameter of type 'ConcatArray<never>'.
      Type 'string' is not assignable to type 'ConcatArray<never>'.
  Overload 2 of 2, '(...items: ConcatArray<never>[]): never[]', gave the following error.
    Argument of type 'never[] | "a"' is not assignable to parameter of type 'ConcatArray<never>'.
      Type 'string' is not assignable to type 'ConcatArray<never>'.(2769)

🙂 Expected behavior

No type errors (except perhaps that the variable may be any until i provide an explicit type for the resulting array), because this is valid JavaScript since at least ES3.

貢獻者指南