Skip to content

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

Closed
@olderor

Description

@olderor

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions