Skip to content

Optional chaining operator infers never in a loopΒ #49542

@VojtaStanek

Description

@VojtaStanek

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions