Skip to content

Incorrect type inference of 'unknown' #38051

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
rav2040 opened this issue Apr 20, 2020 · 2 comments
Closed

Incorrect type inference of 'unknown' #38051

rav2040 opened this issue Apr 20, 2020 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@rav2040
Copy link

rav2040 commented Apr 20, 2020

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

@MartinJohns
Copy link
Contributor

Duplicate of #37658.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Apr 20, 2020
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants