Skip to content

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

Closed
@wil93

Description

@wil93

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions