Microsoft/TypeScript

Incorrectly reported `TS2322` error on array items after spread

Open

#55,340 建立於 2023年8月11日

在 GitHub 查看
 (1 留言) (0 反應) (0 負責人)TypeScript (6,726 fork)batch import
BugDomain: Error MessagesHelp Wanted

倉庫指標

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

描述

🔎 Search Terms

"array spread", "TS2322"

🕗 Version & Regression Information

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

⏯ Playground Link

https://www.typescriptlang.org/play?#code/MYewdgzgLgBAhgLhgQQE6rgTwDxgK4C2ARgKaowA+M0qAlmAOYB8MAvDANoC6A3AFChIsIkjQYc+YmRbsOAOgVwANDACMvIA

💻 Code

const a: Array<number | string> = [];
const b: Array<number> = [...a, 1];

🙁 Actual behavior

The compiler gives the following two errors, of which only one is appropriate:

~/prog/typescript ❯ tsc ./array-spread-error.ts
array-spread-error.ts:2:27 - error TS2322: Type 'string | number' is not assignable to type 'number'.
  Type 'string' is not assignable to type 'number'.

2 const b: Array<number> = [...a, 1];
                            ~~~~

array-spread-error.ts:2:33 - error TS2322: Type 'string | number' is not assignable to type 'number'.
  Type 'string' is not assignable to type 'number'.

2 const b: Array<number> = [...a, 1];
                                  ~

🙂 Expected behavior

The spread is clearly incorrect, as the original array could potentially contain strings as well, but the number literal should not be marked with the same error.

貢獻者指南