Microsoft/TypeScript
GitHub ã§èŠãOptional chaining operator infers `never` in a loop
Open
#49,542 opened on 2022幎6æ14æ¥
BugDomain: check: Control FlowHelp Wanted
Repository metrics
- Stars
- Â (48,455 stars)
- PR merge metrics
-  (å¹³åããŒãž 6d 17h) (30d ã§ 9 merged PRs)
説æ
Bug Report
ð Search Terms
- optional chaining
ð Version & Regression Information
It's broken in all tested versions of typescript (3.7 until 4.8 nightly in TS playground). Versions prior 3.7 do not support optional chaining.
⯠Playground Link
Playground link with relevant code
ð» Code
function foo(input: boolean[]) {
let acc: null | { prop?: boolean } = null
for (const item of input) {
acc = { prop: item || acc?.prop } // <- Property 'prop' does not exist on type 'never'.
}
}
ð Actual behavior
It infers never for acc variable, thus gives an error:
Property 'prop' does not exist on type 'never'.
function foo(input: boolean[]) {
let acc: null | { prop?: boolean } = null
for (const item of input) {
acc = { prop: item || acc?.prop } // <- Property 'prop' does not exist on type 'never'.
}
}
ð Expected behavior
To work and not to give an error (infer boolean for prop property) - the same way as does this equivalent code:
function foo(input: boolean[]) {
let acc: null | { prop?: boolean } = null
for (const item of input) {
acc = { prop: item || (acc !== null ? acc.prop : undefined) }
}
}