Closed
Description
TypeScript Version: nightly (2.3.0-dev.20170217)
The problem
Currently it is possible to assert an expression of one literal type to be of a different literal type.
const True = false as true;
const one = 2 as 1;
const str = 'hello' as 'str';
This is confusing and obviously incorrect. It also diverges from the behaviour exhibited when checking literal properties and array elements. The following cases raise errors as expected.
['hello'] as ['str']; // Type "hello" is not comparable to type "str"
({a: 'hello'} as {a: 'str'}); // Type "hello" is not comparable to type "str"
It's been written many times that assertions provide a mechanism to either upcast or downcast, however in the specific case of mismatching literal types, the operation is actually coercion because they are on the same level.
Proposal
No literal widening should be carried out prior to the assertion compatibility check iff the expression type is a string, number or boolean literal and the assertion type is
- a literal of the same base type
- or, a union or intersection containing a constituent of the same base type
Examples
false as (false | string); // OK
false as (true | string); // Error
false as (boolean | string); // OK
'hello' as 'str'; // Error
'hello' as 'hello'; // OK
'hello' as ('str' | 123); // Error
'hello' as ('hello' | 123); // OK
'hello' as (1 | 2 | string); // OK
'hello' as ('str' & { _brand: any }); // Error
'hello' as ('hello' & { _brand: any }); // OK
'hello' as ('str' & { _brand: any } | 1); // Error
'hello' as ('hello' & { _brand: any } | 1); // OK