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

Number.isInteger is no longer type guarding #53295

Closed
tkolanko opened this issue Mar 16, 2023 · 3 comments
Closed

Number.isInteger is no longer type guarding #53295

tkolanko opened this issue Mar 16, 2023 · 3 comments

Comments

@tkolanko
Copy link

Bug Report

πŸ”Ž Search Terms

isInteger
type guard

πŸ•— Version & Regression Information

5.0.2

NOTE: there is no 5.0.2 version on the playground so I selected nightly

  • This changed between versions 4.9.5 and 5.0.2

⏯ Playground Link

5.1.0 Playground

4.9.5 Playground

πŸ’» Code


type State = string | number

const makeState = (): State => {

    if (Math.random() > 0.5) {
        return 123;
    }
    return 'abc';

}


const value = makeState();
//    ^?

if (Number.isInteger(value)) {
    console.log(value < 10)
}

const valueIsNumber = (v: any): v is number => {
    return Number.isInteger(v);
}

if (valueIsNumber(value)) {
    console.log(value < 10)
}

πŸ™ Actual behavior

Number.isInteger guards are no longer inferring that a value is a number

πŸ™‚ Expected behavior

Number.isInteger should type guard

@MartinJohns
Copy link
Contributor

Number.isInteger was never type guarding. In your 4.9 playground you can see in line 18 that value is still typed State, not number. But TypeScript 5.0 now forbids implicit coercions in relational operators, resulting in the error you see.

@fatcerberus
Copy link

btw it can’t be changed to v is number because type guards work in both directions (i.e. returning false implies it’s not a number). See #15048

@tkolanko
Copy link
Author

ah ok thanks - I understand now

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants