Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

typeof discards previous non-null checks #28131

Copy link
Copy link
@mgol

Description

@mgol
Issue body actions

TypeScript Version: 3.2.0-dev.20181025

Search Terms:
unknown typeof object null

Code

Run the following code via tsc --noEmit --strict test.ts

declare const x: unknown;
x !== null && typeof x === 'object' && 'field' in x;

Expected behavior:
It should pass the type check as the first condition ensures x is not null and the second one narrows the type to object | null. Together with the previous non-null check it should result in the object type.

Actual behavior:

test.ts:2:42 - error TS2531: Object is possibly 'null'.

2 x && typeof x === 'object' && 'field' in x;
                                           ~

A workaround is to switch the order of typeof and the x truthiness check:

declare const x: unknown;
typeof x === 'object' && x !== null && 'field' in x;

Playground Link: Note: you need to enable strictNullChecks manually!
https://www.typescriptlang.org/play/#src=declare%20const%20x%3A%20unknown%3B%0D%0Ax%20!%3D%3D%20null%20%26%26%20typeof%20x%20%3D%3D%3D%20'object'%20%26%26%20'field'%20in%20x%3B%0D%0A

Related Issues: #27180

Reactions are currently unavailable

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptA bug in TypeScriptFix AvailableA PR has been opened for this issueA PR has been opened for this issue

Type

No type
No fields configured for issues without a type.

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions

    Morty Proxy This is a proxified and sanitized view of the page, visit original site.