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

Boolean() breaks strict null check #30367

Closed
fetis opened this issue Mar 13, 2019 · 2 comments
Closed

Boolean() breaks strict null check #30367

fetis opened this issue Mar 13, 2019 · 2 comments

Comments

@fetis
Copy link

fetis commented Mar 13, 2019

TypeScript Version: 3.4.0-dev.201xxxxx

Search Terms:
Boolean strictNullChecks

Code
Pre-requirements: you need to have strictNullChecks enabled;

export interface Price {
  price?: {
    value: number
  };
}

const a: Price = {};

if (a.price) {
  console.log(a.price.value);  // works as expected
}

if (Boolean(a.price)) {
  console.log(a.price.value);  // throws an error for a.price, Object is possible undefined
}

Expected behavior:
I would be expecting this check also works.

Actual behavior:
Actually, it brings an error Object is possible undefined.

I think it's caused by the fact the Boolean() internally convert its argument to any, so TS lost check for real value for type Price. The same behavior can be achieved with if (a.price as any).
It would be nice to have it fixed, but I'm not sure is it really possible.

Playground Link: https://www.typescriptlang.org/play/index.html#src=export%20interface%20Price%20%7B%0D%0A%20%20price%3F%3A%20%7B%0D%0A%20%20%20%20value%3A%20number%0D%0A%20%20%7D%3B%0D%0A%7D%0D%0A%0D%0Aconst%20a%3A%20Price%20%3D%20%7B%7D%3B%0D%0A%0D%0Aif%20(Boolean(a.price)%20%7B%0D%0A%20%20console.log(a.price.value)%3B%20%20%2F%2F%20a.price%20Object%20is%20possible%20undefined%0D%0A%7D%0D%0A

@j-oliveras
Copy link
Contributor

Duplicate of #16655? PR for that on #29955.

@fetis
Copy link
Author

fetis commented Mar 13, 2019

@j-oliveras yeah, it's duplicate.

@fetis fetis closed this as completed Mar 13, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants