microsoft / microsoft/TypeScript
Allow narrowing of unions discriminated by numeric literals using `>` `<` etc
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
🔎 Search Terms
"arguments length"
🕗 Version & Regression Information
It works the same in v3.3.3
⏯ Playground Link
💻 Code
Some basic ways to check if we have any arguments could be these:
function example1(...args: [number] | []) {
if (args.length > 0) {
return args[0];
} else {
return NaN;
}
}
function example2(...args: [number] | []) {
if (args.length) {
return args[0];
} else {
return NaN;
}
}
function example3(...args: [number] | []) {
if (args.length === 0) {
return NaN;
} else {
return args[0];
}
}
But TS doesn't seem to understand the first one.
🙁 Actual behavior
It doesn't understand the way it's done in "example1".
🙂 Expected behavior
It should understand the way it's done in "example1".
Additional information about the issue
Type inference on "args" after the check for "example1":
Type inference on "args" after the check for "example2":
Type inference on "args" after the check for "example3":
Notice how for "example2" and "example3" the type is correctly narrowed to just [number], but for "example1" the unnarowed [number] | [] type remains.
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
Use the linked TypeScript Playground examples as the entry point; compare control-flow narrowing for args.length > 0 with the existing truthiness and equality cases. Done means example1 narrows [number] | [] to [number] in the true branch without losing the behavior shown by examples 2 and 3.
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
- Clearly specified
- Newbie friendliness
- 35/100