Typescript: Destructuring an optional property with union containing literal type should not be widen if the default value is compatible with the union

Created on 16 Dec 2019  路  5Comments  路  Source: microsoft/TypeScript

TypeScript Version: 3.8.0-dev.20191214

Search Terms: union, default value, literal, destructuring, optional

It surprised me a little bit not finding a duplicate myself. This is a frequent issue for us, though most of the time we can "fix" it with type assertion.

Code

interface Foo {
  bar: 'yo' | 'ha' | undefined;
}

let { bar = 'yo' } = {} as Foo;

bar; // expecting `bar` to be `'yo' | 'ha'`, but gets `string` instead

Playground Link: http://www.typescriptlang.org/play/?ts=3.8.0-dev.20191214#code/JYOwLgpgTgZghgYwgAgGIHt3IN4ChnIBGcUAXMgOQCe6FyAPpQBZx2MCuIAJhDKBFwDcuAL65cAGwhgcREsgC8lGnRGKcauAGc0mYbmJRByAPQnkEAB4AHCAjCgA5sgAGhl8jBZCKF9VoMzKwuADRE7DKO0jouWmBQTh6gcRBwXEA

Related Issues:

Bug Fix Available

Most helpful comment

My immediate thought is that this is supposed to be equivalent, but isn't:

let bar = ({} as Foo).bar ?? 'yo';  // 'yo' | 'ha'

So, it seems like a fix is merited.

All 5 comments

You should be using let { bar = 'yo' as const } = {} as Foo;, otherwise that 'yo' is just string value rather than the literal type yo.

Updated example: https://www.typescriptlang.org/play/index.html?ssl=1&ssc=1&pln=77&pc=72#code/JYOwLgpgTgZghgYwgAgGIHt3IN4FgBQyyARnFAFzIDkAnulcgD7UAWcDzAriACYQygIPANwEAvgQIAbCGBwkyyALzU6DOAGdkCdCA1yxynIc1pMo-AVJRhyAPR3kEAB4AHCAjCgA5sgAG1n7IYFjEKH609Eys7H4ANCScct6yWn76UD5BoPoQcDxAA

@rusev I am not looking for a workaround though. The compiler itself should just do the job without extra hint.

I'm 100% with you, but I think this is intended behavior :).

@ahejlsberg thoughts?

My immediate thought is that this is supposed to be equivalent, but isn't:

let bar = ({} as Foo).bar ?? 'yo';  // 'yo' | 'ha'

So, it seems like a fix is merited.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

siddjain picture siddjain  路  3Comments

CyrusNajmabadi picture CyrusNajmabadi  路  3Comments

Roam-Cooper picture Roam-Cooper  路  3Comments

manekinekko picture manekinekko  路  3Comments

blendsdk picture blendsdk  路  3Comments