Skip to content

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

Closed

Description

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

Activity

  1. MartinJohns commented on Jul 18, 2020

    @MartinJohns
    Contributor

    Duplicate of #12184.

  2. sandinmyjoints commented on Jul 18, 2020

    @sandinmyjoints
    Author

    Well, now I know what should have searched for 😆

  3. typescript-bot commented on Jul 21, 2020

    @typescript-bot
    Contributor

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

  4. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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