Skip to content

Array concat has wrong types #47351

@ljharb

Description

@ljharb

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptDomain: lib.d.tsThe issue relates to the different libraries shipped with TypeScriptHelp WantedYou can do this

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions