Skip to content

[Suggestion] Disallow literal types to be asserted to a different literal type of the same widened type #14156

Closed
@gcnew

Description

@gcnew

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions