GeezerVison is showing github.com — Narrow string and number types in literal equality checks by ahejlsberg · Pull Request #11587 · microsoft/TypeScript
Conversation
With this PR we narrow the string and number types as appropriate when they are compared with values of literal types.
function move(direction: "up" | "down") {
// ...
}
function do1(command: string) {
if (command === "up" || command === "down") {
move(command); // Narrowed to type "up" | "down"
}
}
function do2(command: string) {
switch (command) {
case "up":
case "down":
move(command); // Narrowed to type "up" | "down"
break;
}
}
function f1(x: number, y: 1 | 2) {
if (x === 0 || x === y) {
x; // Narrowed to type 0 | 1 | 2
}
}
function f2(x: number | "foo" | "bar", y: 1 | 2 | string) {
if (x === y) {
x; // Narrowed to type "foo" | "bar" | 1 | 2
y; // Narrowed to type "foo" | "bar" | 1 | 2
}
}
Interestingly this found a bug in our scanner, pointing out that type 2 is not comparable to type 8.
Fixes #7447.
Fixes #10417.
Fixes #11306.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
HerringtonDarkholme, tinganho, normalser, aluanhaddad, robertknight, tekacs, malekpour, rictic, GoToLoop, SlurpTheo, and nikeee reacted with thumbs up emoji
rictic and GoToLoop reacted with hooray emoji
All reactions
-
👍
11 reactions
-
🎉
2 reactions
|
i am not at the computer to check, but would it fix #11433 as well?
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
i am not at the computer to check, but would it fix #11433 as well?
nope. that is a different issue.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Reviewers
1 more reviewer
Reviewers whose approvals may not affect merge requirements
Uh oh!
There was an error while loading. Please reload this page.
Assignees
No one assigned
Milestone
No milestone
Development
Successfully merging this pull request may close these issues.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
|