Microsoft/TypeScript

Optional chaining operator infers `never` in a loop

Open

#49.542 aberto em 14 de jun. de 2022

Ver no GitHub
 (1 comment) (0 reactions) (0 assignees)TypeScript (6.726 forks)batch import
BugDomain: check: Control FlowHelp Wanted

Métricas do repositório

Stars
 (48.455 stars)
Métricas de merge de PR
 (Mesclagem média 6d 17h) (9 fundiu PRs em 30d)

Description

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

Guia do colaborador