Skip to content

Order of x !== null and typeof x === "object" produce different guards #40661

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

Closed
kraenhansen opened this issue Sep 20, 2020 · 2 comments
Closed

Comments

@kraenhansen
Copy link

TypeScript Version: 4.1.0-dev.20200920

Search Terms: type guard unknown null typeof object

Code

declare const something: unknown;

let obj: object;

if (typeof something === "object" && something !== null) {
    // Works fine ✓
    obj = something;
}

if (something !== null && typeof something === "object") {
    // 💥 Type 'object | null' is not assignable to type 'object'.
    obj = something;
}

Expected behavior:

The order in which the type not null guard and a typeof guard is applied, should not matter since none of them have side-effects and the and operator is commutative.

Actual behavior:

When applying a "strict not null" (!== null) type guard before a typeof object guard (typeof .. === "object") the not null guard is forgotten.

Playground Link: Link to playground.

Related Issues: This is the closest I got #32798, but it seems to be caused specifically by a non-strict equal operator.

@IllusionMH
Copy link
Contributor

Duplicate of #28131. Found with null typeof object

@kraenhansen
Copy link
Author

Thanks for digging that issue up for me! I will close this and watch the other.

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

2 participants