microsoft / microsoft/TypeScript
Narrow number literal types with comparison
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
Search Terms
constant number literals narrowing comparison
Suggestion
Narrow number literal type not only with (non)equality, but also with less-than etc.
This request is only about throwing away non-matching literals, and not about full-blown number narrowing.
Use Cases
This could be used to direct narrowing with tuple unions.
Examples
With literals
type X = 0 | 1 | 2 | 3;
function f(): X {
return 1;
}
function g(x: 0 | 3) {
console.log(x);
}
let x: X = f();
g(x); // Error, 1 | 2 is unexpected
if (x > 2) {
g(x); // Same error, but should be safe
}
if (x != 1 && x != 2) {
g(x); // Ok
}
With tuples
type X = [] | [string, string];
function f(): X { return [];}
function g(x: string) {
console.log(x);
}
let x: X = f();
g(x[0]); // Error, undefined is unexpected
if (x.length > 0) {
g(x[0]); // Error, but should be ok
}
if (x.length == 2) {
g(x[0]); // Ok
}
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
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 literal and tuple examples in the issue, reproducing their current diagnostics and narrowing behavior. Define the expected control-flow results for comparison checks, including less-than and tuple-length comparisons, and verify that the change only removes impossible literal cases without introducing general number narrowing.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100