Skip to content

Type predicates only work with shorthand syntax in if statementsΒ #49573

@ngregory-rbi

Description

@ngregory-rbi

Bug Report

πŸ”Ž Search Terms

predicate
type predicate
predicate syntax

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about type predicates.

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

function a() {
    const validFlags = ['-a', '-b', '-c'] as const;
    function isFlagValid(flag: string): flag is typeof validFlags[number] {
        return validFlags.includes(flag as typeof validFlags[number]);
    }
    const flag = Math.random().toString();
    if (isFlagValid(flag) === false) {
        flag; // string
        return;
    }
    flag; // string

    if (!isFlagValid(flag)) {
        flag; // string
        return;
    }
    flag; // typeof validFlags[number]
}

function b() {
    const validFlags = ['-a', '-b', '-c'] as const;
    function isFlagValid(flag: string): flag is typeof validFlags[number] {
        return validFlags.includes(flag as typeof validFlags[number]);
    }
    const flag = Math.random().toString();
    if (isFlagValid(flag) === true) {
        flag; // string
        return;
    }
    flag; // string
    
    if (isFlagValid(flag)) {
        flag; // typeof validFlags[number]
        return;
    }
    flag; // string
}

πŸ™ Actual behavior

The function with a type predicate only limits the type definition of flag if it's used in shorthand syntax !isFlagValid(flag) or isFlagValid(flag) and not the more explicit isFlagValid(flag) === false or isFlagValid(flag) === true.

πŸ™‚ Expected behavior

The function with a type predicate limits the type definition of flag regardless of the syntax uses and they both mean the same thing.

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