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

贡献者指南