why is TypeScript converting string literal union type to string when assigning in object literal?

后端 未结 3 700
一个人的身影
一个人的身影 2020-12-11 10:16

I love string literal union types in TypeScript. I came across a simple case where I was expecting the union type to be retained.

Here is a simple version:



        
3条回答
  •  爱一瞬间的悲伤
    2020-12-11 10:41

    To answer the updated question with three-value literal union type:

    type Status = 'foo' | 'bar' | 'baz';
    let foo = false;
    const bar: Status = foo ? 'foo' : 'bar';
    

    Declared type of bar is Status, but it's inferred type is still narrowed by control flow analysis to only two possible values out of three, 'foo' | 'bar'.

    If you declare another variable without a type, TypeScript will use inferred type for bar, not the declared type:

    const zoo = bar; // const zoo: "foo" | "bar"
    

    Without resorting to type assertion as Status, there's no way to turn off type inference based on control flow analysis other than explicitly declaring the type at the place where you need it:

    const foobar: {bar: Status} = {
        bar // has Status type now
    }
    

提交回复
热议问题