Microsoft/TypeScript

Optional chaining operator infers `never` in a loop

Open

#49.542 geöffnet am 14. Juni 2022

Auf GitHub ansehen
 (1 Kommentar) (0 Reaktionen) (0 zugewiesene Personen)TypeScript (6.726 Forks)batch import
BugDomain: check: Control FlowHelp Wanted

Repository-Metriken

Stars
 (48.455 Stars)
PR-Merge-Metriken
 (Durchschn. Merge 6T 17h) (9 gemergte PRs in 30 T)

Beschreibung

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) }
	}
}

Contributor Guide