Skip to content

Type is lost when result of type guard is assigned and strictNullChecks is on #39657

Closed
@sandinmyjoints

Description

@sandinmyjoints

TypeScript Version: seen in 3.8.3, 3.9.2, 3.9.3, nightly

Search Terms: "jsdoc" "typescript" "strictnullcheck" "type guard"

Code

// @ts-check

// NOTE: Problem only happens when strictNullChecks is on. 
// repro: https://www.typescriptlang.org/play?strictNullChecks=true&ts=3.9.3&useJavaScript=true#

/**
 *
 * @typedef Thing
 * @property {number} id
 */

/**
 * @param {Thing|null} variable
 * @return {variable is Thing}
 */
const isNotNull = variable => variable !== null;

/**
 * @param {Thing|null} thing
 */
const fn = thing => {
  thing; // as expected, type is Thing | null

  if (isNotNull(thing)) {
    thing; // as expected, type is Thing
    thing.id; // no error
  }

  const isAvailable = isNotNull(thing);
  if (isAvailable) {
    thing; // unexpected: type is Thing | null
    thing.id; // error: Object is possibly null
  }
};

Expected behavior:
In the body of the second if, thing will be typed as Thing.

Actual behavior:
In the body of the second if, thing is typed as Thing | null

Playground Link: https://www.typescriptlang.org/play?strictNullChecks=true&ts=3.9.2&useJavaScript=true

Related Issues: no

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