Skip to content
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

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

Closed
sandinmyjoints opened this issue Jul 18, 2020 · 3 comments · Fixed by #44730
Closed

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

sandinmyjoints opened this issue Jul 18, 2020 · 3 comments · Fixed by #44730
Labels
Duplicate An existing issue was already created

Comments

@sandinmyjoints
Copy link

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

@MartinJohns
Copy link
Contributor

Duplicate of #12184.

@sandinmyjoints
Copy link
Author

Well, now I know what should have searched for 😆

@orta orta added the Duplicate An existing issue was already created label Jul 18, 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

Successfully merging a pull request may close this issue.

4 participants