Reputation: 21400
In TypeScript I can successfully compile following code:
const x = true as false;
So I have a constant x
with value true
and type false
. I expected that such direct assertions should be invalid, but surprisingly it is valid. For example, for the similar code
const x = 0 as false;
there is a compilation error
Conversion of type 'number' to type 'false' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
I expected a similar error to occur with true
and false
.
Why there is no error and is there a way (like some set of compiler options) to fix it?
Upvotes: 3
Views: 222
Reputation: 673
It's because typescript expands the types themselves. true and false do overlap, they are both boolean types. 0 and false don't overlap, one is a number, the other a boolean.
Upvotes: 4