Skip to content

Incorrect type inference of 'unknown' #38051

Closed
@rav2040

Description

@rav2040

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:

  1. typeof foo === 'object'
  2. 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions