Skip to content

Allow == null to narrow unknown to null | undefined #32798

Closed
@ericyhwang

Description

@ericyhwang

TypeScript Version: typescript@3.6.0-dev.20190809

Search Terms: unknown, type guard, double-equals, ==, null

Code

Minimal repro case:

export function test(v: unknown) {
  let nullOrUndefined: null | undefined;
  if (v === null || v === undefined) {
    // This works, as `v` is narrowed to `null | undefined`.
    nullOrUndefined = v;
  }
  if (v == null) {
    // Error: Type 'unknown' is not assignable to type 'null | undefined'.
    nullOrUndefined = v;
  }
}

A more practical use-case for the narrowing would be something like this:

if (typeof v === 'string' || v == null) {
  // v should be `string | null | undefined` in here.
  if (v) {
    // v is a non-empty string
    doSearch(v);
  } else {
    // v is empty string, null, or undefined
    clearSearch();
  }
}

Expected behavior:

v == null narrows an unknown type to null | undefined, same as v === null || v === undefined does.

Reading the ECMAScript spec on ==, I believe that == null will guarantee that the value is either null or undefined. == undefined would do the same thing, though linters generally prefer the shorter == null.

Actual behavior:

Compile error:

src/index.ts:11:5 - error TS2322: Type 'unknown' is not assignable to type 'null | undefined'.
  Type 'unknown' is not assignable to type 'null'.

11     nullOrUndefined = v;
       ~~~~~~~~~~~~~~~

Found 1 error.

Playground Link: https://www.typescriptlang.org/play/#code/KYDwDg9gTgLgBAMwK4DsDGMCWEVxsAZxgAoA3ALjlQGsUIB3FASjgG8AoOOAG2HhSTduAeSgBVFABNgCTCmCTKAoXAA+VKTLkKA3JziYEcMnAC85uMu5r1pMxdTTZ8ySw5cuAek9wAKgAtMAjh6aGoCADp9LitRCSdtSTM4Uj0uAF99Q2M7Cys3aLhvPwBPMGA4AHIaOkZKg2C6eABDAgJMAHMUZoAjXjwIPDKKyqs1DQSXSqiPS0ERcU1nBWTU-UzMoA

Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions