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 guarding against BigInt using typeof not working - but using instanceof works, even though that javascript code will not work #58225

Closed
arnorhs opened this issue Apr 17, 2024 · 1 comment

Comments

@arnorhs
Copy link

arnorhs commented Apr 17, 2024

πŸ”Ž Search Terms

bigInt typeof, bigint instanceof

πŸ•— Version & Regression Information

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

⏯ Playground Link

https://www.typescriptlang.org/play?target=99&ts=5.5.0-dev.20240417#code/FAMwrgdgxgLglgewgAgggQnA5gSQjAVQGc4IsAVATwAcBTAeRAAoA3AQwBsAuVMAWwBGtAE7IAPsky58ASh5EYw0lnG9BI1RDAcOyAN7BkR5AHoTyKnVRthwhAHdlyOEVQIYyKAlu1YAGmQBMA8YAAsXTwQAE1pkKIRaV3jke1C2DzgPDgQEAGtXDjhc2kNjOBBkJhgaWgQK9l0AXmbkAHIBbFIYVpl9UuNjYVoYMGEULR1+5ABfZFoOIliDAYGhkbHkBqnp4B3QSFhEcYxsPEISMjwFNmgGZgaeLXVRCSkzuWQFJTJNfiEX3g6PoDMwWGrWWwOJwRLw+fyBYKfUhQWJhGHRWLxRIQVoeezeXIBTLOVxsWBgTgcSgpOxkKblSoNZwQa63OqSU6yYErIxrUbjbQcbZzBZLKarYb8zacba7YDAIA

πŸ’» Code

function noBigIntUsingTypeOf(val: number | BigInt): string | number | null {
    // Type narrowing is not correct, but this code does do what it looks like
    if (typeof val === 'bigint') {
        return null
    } else {
        return val
    }
}

function noBigIntUsingInstanceOf(val: number | BigInt): string | number | null {
    // Type narrowing is correct, but since this code doesn't work, it is actually wrong
    if (val instanceof BigInt) {
        return null
    } else {
        return val
    }
}

πŸ™ Actual behavior

typescript believes the typeof val === 'bigint' check does not narrow the type down, when in reality (JS) it does - and similarly for the instanceof case, typescript believes the type to be narrowed down, when reality (JS) it does not work at all

πŸ™‚ Expected behavior

typeof val === 'bigint' would narrow the type down to not include BigInt

Additional information about the issue

No response

@arnorhs arnorhs closed this as completed Apr 17, 2024
@arnorhs
Copy link
Author

arnorhs commented Apr 17, 2024

im so stupid.. bigint is not BigInt

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

1 participant