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
TypeScript Version: 3.4.0-dev.201xxxxx
Search Terms:
Boolean strictNullChecks
Code
Pre-requirements: you need to have
strictNullChecksenabled;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 toany, so TS lost check for real value for typePrice. The same behavior can be achieved withif (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