-
Notifications
You must be signed in to change notification settings - Fork 13.2k
Description
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