Microsoft/TypeScript

Narrow subtype-reduction-prone unions to their narrowest constituent

Open

#47,731 opened on 2022年2月3日

GitHub で見る
 (6 comments) (1 reaction) (0 assignees)TypeScript (6,726 forks)batch import
BugDomain: check: Control FlowHelp Wanted

Repository metrics

Stars
 (48,455 stars)
PR merge metrics
 (平均マージ 6d 17h) (30d で 9 merged PRs)

説明

Bug Report

Type narrowing doesn't seem to take into account an assignment I made to ensure the variable has the right type.

Maybe related? https://github.com/microsoft/TypeScript/issues/43584#issuecomment-816932485

🔎 Search Terms

type narrowing assignment

🕗 Version & Regression Information

4.5.4

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

⏯ Playground Link

Playground Link

💻 Code

declare let a: object | any[] | undefined

if (a === undefined) {
    a = [] // I expect this line to have TS understand that a is any[] from now on
} else if (!Array.isArray(a)) {
    throw new Error()
}
[...a] // complains here because a is object | any[]

🙁 Actual behavior

a has type object | any[]

🙂 Expected behavior

a to have type any[]

コントリビューターガイド