Repository navigation
Recent --strictNullChecks issue w/ && || type result check #9113
Description
Activity
1 more example:
function sq(n?: number): number { const r = n !== undefined && n*n || 0; return r; } alert(sq(3));
sq.ts(3,9): error TS2322: Type 'number | boolean' is not assignable to type 'number'.
Type 'boolean' is not assignable to type 'number'.Reacted by Ulrik StridI see what's going on here. The issue is that we give the sub-expression
sinOrCos && Math.sinthe type((x: number) => number) | boolean. Since the result could be the boolean valuefalse, this is technically not wrong. But it is a little bit too permissive. The type really should be((x: number) => number) | false, meaning that the only the boolean valuefalseis possible. We should likewise returnT | 0andT | ""for&&operations where the first operand is of type number or string respectively.Then we should furthermore say that in an
x || yoperation, we remove the definitely-falsy types (undefined,null,void,false,0, and"") from the type ofxin the resulting union type.Now, the only problem with this solution is that we don't (yet) support boolean literal types or numeric literal types. This means we need to do one of the following:
- Add support for boolean and numeric literal types now.
- Back out Improve typing of && operator with --strictNullChecks #8949 and add support for boolean and numeric literal types later.
Adding Mohamed Hegazy (@mhegazy) and Ryan Cavanaugh (@RyanCavanaugh).
Reacted by GoToLoopAdd support for boolean and numeric literal types now.
👍
Reacted by Eyas, Sean Vieira, Troy Gerwien and Tanguy Le Barzicand numeric ranges:
type Positive = number > 0;Numeric ranges? Are those even possible? That'd be über cool though.
I always wanted to use boolean literals for overloaded functions just like strings do.
I wonder whether those proposed numeric literals would include enums as well?
But of course the most important thing now is to have the&&+||archaic idiom back under --strictNullChecks! :P- addedFixedA PR has been merged for this issueA PR has been merged for this issue
on Jun 15, 2016 - locked and limited conversation to collaborators
on Jun 19, 2018
About 1 weak ago, this sample below would transpile flawlessly under --strictNullChecks:
But to my surprise today, under typescript@1.9.0-dev.20160612-1.0, only the statement using the ternary conditional operator works now!
Somehow TS thinks that choice could be
booleanas well when using&&+||expression. =(Is that intentional from now on? I miss when it was smarter just 1 week ago. :-(
tsc --pretty --newLine LF --removeComments --experimentalDecorators --strictNullChecks -d -t ES6 sinCos