microsoft / microsoft/TypeScript

Type narrowing fails to account for multiple conditions

Open
#53,072 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

Bug Report

🔎 Search Terms

type narrowing

🕗 Version & Regression Information
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about _________
⏯ Playground Link

https://tsplay.dev/mAJ91W

💻 Code
function isNaN(x: unknown): x is number {
	return x !== x;
}
function SameValue(x: unknown, y: unknown): x is typeof y {
	if (x === y) { // 0 === -0, but they are not identical.
		if (x === 0) { return 1 / x === 1 / y; }
		return true;
	}
	return isNaN(x) && isNaN(y);
};
🙁 Actual behavior

The y in 1 / y has a type error.

🙂 Expected behavior

Since this is inside a block where x === y, and also where x === 0, TS should be able to statically know that x and y are of type number (since both of them is definitively a zero, either +0 or -0). I shouldn't need the y === 0 check just to please TS.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the narrowing behavior in the linked TypeScript Playground using the provided SameValue example, then start by tracing how the checker handles the nested x === y and x === 0 conditions. Done means the existing 1 / y expression type-checks without adding a separate y === 0 check, with coverage for the reported case.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.