Skip to content

Allow narrowing of unions discriminated by numeric literals using > < etc #61770

Open
@fabiospampinato

Description

@fabiospampinato

πŸ”Ž Search Terms

"arguments length"

πŸ•— Version & Regression Information

It works the same in v3.3.3

⏯ Playground Link

https://www.typescriptlang.org/play/?target=99&module=0&ts=5.8.3#code/GYVwdgxgLglg9mABAUwB4EMC2AHANsgRgAoA6M9AJwHMBnALkQG0wRMAjZCgXUQB8muASkQBvAFCJJiGMERFKtEvjBUoAC0QA+RAAZh4qYcQVkUEBSQKajHVwDcEqQF8UuGslGOjx0+aQA5dH8HQycxMNBIWAQUDBx8ACZScmp6JhZ2Th5+RiFPQxk5KyVkFXV9LyMTMwtEKxt7SpdkNw8Dbx8agKCQ53CxSOh4JDQsPGQAZmSSKwZmVg5uPgEKgtl5VJKyjQBePd1Vjuq-REDgptd3fKPfWvrbXskwpyA

πŸ’» 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":

Image

Type inference on "args" after the check for "example2":

Image

Type inference on "args" after the check for "example3":

Image

Notice how for "example2" and "example3" the type is correctly narrowed to just [number], but for "example1" the unnarowed [number] | [] type remains.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions