Skip to content

Type guard against 'unknown' fails to narrow down to 'object' when using an if statement with the OR condition #38814

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
wil93 opened this issue May 27, 2020 · 2 comments

Comments

@wil93
Copy link

wil93 commented May 27, 2020

TypeScript Version: 3.9.2

Search Terms: null object unknown

Code

declare const data: unknown;

if (data === null || typeof data !== 'object') {
    throw Error();
}

data;

Expected behavior: the 'data' const should be of type object.

Actual behavior: the 'data' const is recognized as type object | null.

Notice that if I split the above condition into two separate if statements, then it works as expected.

Playground Link:

Version showcasing the bug: https://www.typescriptlang.org/play/#code/CYUwxgNghgTiAEYD2A7AzgF3sKGoC54BXFAaxSQHcUBuAKDoEsAzeAChz3gF5f4UiECPAA+I+BgCeABxBJWnKPACEfAORIARgCtwGNQEp4AbzrxzEgBYwq8AKIwbMNgfoBfBoppA

And here's the (working) version with separate if statements: https://www.typescriptlang.org/play/#code/CYUwxgNghgTiAEYD2A7AzgF3sKGoC54BXFAaxSQHcUBuAKDoEsAzeACgwE8AHEJVnHngBCALyj4AciQAjAFbgMkgJTwA3nXhb4GABYwq8AKIwDMNsvoBfBi3aCo8cRJREIEVRu079hk2YtrBgcaIA

Related Issues: none found

@jack-williams
Copy link
Collaborator

This is a duplicate of #28131, just with the logic negated.

@wil93
Copy link
Author

wil93 commented May 27, 2020

Right, it's the same issue.

@wil93 wil93 closed this as completed May 27, 2020
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