Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type guard does not work correctly with empty string type #42101

Closed
olderor opened this issue Dec 24, 2020 · 2 comments · Fixed by #49625
Closed

Type guard does not work correctly with empty string type #42101

olderor opened this issue Dec 24, 2020 · 2 comments · Fixed by #49625
Labels
Duplicate An existing issue was already created

Comments

@olderor
Copy link

olderor commented Dec 24, 2020

Bug Report

🔎 Search Terms

type guard

🕗 Version & Regression Information

TypeScript 3.3.3+ (as per playground)

Please keep and fill in the line that best applies:

⏯ Playground Link

Playground link with error

Playground link without error but with incorrect type

💻 Code

The compiled JavaScript version works correctly, but TypeScript gives errors:

type EmptyString = '' | null | undefined;

function isEmpty(value: string | EmptyString): value is EmptyString {
    return value === '' || value === null || value === undefined;
}

let test: string | null | undefined;

if (isEmpty(test)) {
    if (test === '') { // Compilation error since test: null | undefined and not test: '' | null | undefined
        console.log('Nope');
    }
}

image

Also, it's weird that when I remove null from the list of types, the error disappears, but the incorrect type is still shown:

type EmptyString = '' | undefined;

function isEmpty(value: string | EmptyString): value is EmptyString {
    return value === '' || value === undefined;
}

let test: string | undefined;

if (isEmpty(test)) {
    if (test === '') { // No errors, but the editor displays incorrect type.
        console.log('Nope');
    }
}

image

🙁 Actual behavior

TypeGuard ignores empty string and thinks the value can only be null or undefined.

🙂 Expected behavior

The type should include empty string. No errors expected.

@MartinJohns
Copy link
Contributor

This looks very similar to #31156.

@andrewbranch andrewbranch added the Duplicate An existing issue was already created label Dec 28, 2020
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
4 participants