Closed
Description
TypeScript Version: 3.8.3
Search Terms:
unknown, null, incorrect, conditional, type inference
Expected behavior:
There should not be an error when using a conditional to correctly narrow down an unknown
variable to a variable of type object
.
Actual behavior:
Given a variable foo
of type unknown
, it is correctly inferred to be of type object
when the following are both true
:
typeof foo === 'object'
foo !== null
However, when the order is swapped, the type of foo
is incorrectly inferred to be of type object | null
.
Related Issues:
Could not find related issues.
Code
const foo = {} as unknown;
let bar: object;
if (typeof foo === 'object' && foo !== null) {
bar = foo; // type of 'foo' is correctly inferred to be 'object'
}
if (foo !== null && typeof foo === 'object') {
bar = foo; // type of 'foo' is incorrectly inferred to be 'object | null'
}
Output
"use strict";
const foo = {};
let bar;
if (typeof foo === 'object' && foo !== null) {
bar = foo; // type of 'foo' is correctly inferred to be 'object'
}
if (foo !== null && typeof foo === 'object') {
bar = foo; // type of 'foo' is incorrectly inferred to be 'object | null'
}
Compiler Options
{
"compilerOptions": {
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictPropertyInitialization": true,
"strictBindCallApply": true,
"noImplicitThis": true,
"noImplicitReturns": true,
"alwaysStrict": true,
"esModuleInterop": true,
"declaration": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"moduleResolution": 2,
"target": "ES2017",
"jsx": "React",
"module": "ESNext"
}
}
Playground Link: Provided