Microsoft/TypeScript

Optional chaining operator infers `never` in a loop

Open

#49,542 建立於 2022年6月14日

在 GitHub 查看
 (1 留言) (0 反應) (0 負責人)TypeScript (6,726 fork)batch import
BugDomain: check: Control FlowHelp Wanted

倉庫指標

Star
 (48,455 star)
PR 合併指標
 (平均合併 6天 17小時) (30 天內合併 9 個 PR)

描述

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

貢獻者指南