Typescript: Type assertion for string literals stopped working

Created on 12 Sep 2016  ·  3Comments  ·  Source: microsoft/TypeScript

TypeScript Version: 2.1.0-dev.20160912

Code

// A *self-contained* demonstration of the problem follows...
const types = {
    test: <'test'>'test',
    test2: 'test2' as 'test2'
} // type: {test: string, test2:string}

let a = <'test'>'test'  // type string

Probably related to: https://github.com/Microsoft/TypeScript/pull/10676

Bug Fixed

Most helpful comment

@wallverb Agreed, it would be nice to have _some_ form of syntax to indicate you don't want widening without having to explicitly state the type. But regardless, for backwards compatibility reasons we should allow type assertions to have that meaning.

All 3 comments

Yes, this is related to #10676. Previously, a string literal would have a literal type only in certain "literal contexts" (such as after a type assertion) and we would just use the exact type of an expression as the inferred type of an object literal property. Now, string literals always have literal types and instead we _widen_ types when they're inferred for mutable locations (such as object literal properties). So, in your example, the type assertions have no effect (a) because the string literals are already of literal types and (b) because we widen the result of the entire expression after the type assertion.

For better backwards compatibility we could consider _not_ widening an inferred type when the initializer expression is a type assertion. After all, what would be the point of the type assertion otherwise?

@ahejlsberg Thank you for the response.

It would be great if you could consider _not_ widening an inferred type when the initializer expression is a type assertion - and agree - that's kind of the point of the type assertion :)

Another common case that will stop working without it is:

function test(style: { align: 'left' | 'right', size: number }) {
}

const style = {
    align: 'left' as 'left',
    size: 5
}

test(style)

Syntax for literal types https://github.com/Microsoft/TypeScript/issues/10195 would help - but I'm not sure if it will ever become a reality

Thanks a lot for everything

@wallverb Agreed, it would be nice to have _some_ form of syntax to indicate you don't want widening without having to explicitly state the type. But regardless, for backwards compatibility reasons we should allow type assertions to have that meaning.

Was this page helpful?
0 / 5 - 0 ratings