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 predicates only work with shorthand syntax in if statements #49573

Closed
ngregory-rbi opened this issue Jun 16, 2022 · 2 comments
Closed

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

ngregory-rbi opened this issue Jun 16, 2022 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@ngregory-rbi
Copy link

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.

@MartinJohns
Copy link
Contributor

Duplicate of #44366.

@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
Development

No branches or pull requests

4 participants