microsoft / microsoft/TypeScript
Type narrowing in loose equality fails for edge cases like empty string and zero
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
TypeScript Version: 3.8.3
Search Terms:
type narrowing loose equality
type guard loose equality
loose comparison empty string zero
non-strict comparison empty string zero
type guard empty string zero
coercion double equals
type guard coercion fails
Code
TS misses edge cases when narrowing down types in loose equality comparisons.
Following the example from the new handbook on Equality narrowing, if you replace the strict equality with a loose equality, you're rocket is ready to explode. If you pass in the empty string and zero the if condition passes and accessing toUpperCase() on a number fails.
function foo(x: string | number, y: string | boolean) {
if (x == y) {
// We can now call any 'string' method on 'x' or 'y'.
x.toUpperCase();
y.toLowerCase();
}
else {
console.log(x);
console.log(y);
}
}
foo(0, "");
It might be worth mentioning, that this is only one out of many edge cases with the loose equality operator. Maybe you want to check more than just my example above. I bet Kyle Simpson (@getify) could give you some more examples.
Expected behavior:
After a loose equality comparison, TS should not narrow down string | number and string | boolean to string, since a number can equal a string in the edge case 0 == "".
Actual behavior:
After a loose equality comparison, TS narrows down string | number and string | boolean to string, even though this is incorrect, as seen for edge cases like 0 == "".
Playground Link: Playground Link
Related Issues:
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked Playground reproduction using TypeScript 3.8.3 and compare the narrowing result with JavaScript's loose-equality behavior for 0 == "". Review the equality-narrowing behavior and related edge cases; done means the checker no longer treats the example as safely narrowed when runtime coercion can make the comparison true.
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
- 32/100