I am a big fan of string literal union types in TypeScript. Recently, I encountered a situation where I expected the union type to be preserved.
Let me illustrate with a simple example:
let foo = false;
const bar = foo ? 'foo' : 'bar';
const foobar = {
bar
}
The variable bar
is correctly typed as 'foo' | 'bar'
:
https://i.sstatic.net/XssIM.png
However, foobar.bar
is being typed as string
:
https://i.sstatic.net/Ssi5q.png
This discrepancy got me thinking.
Update
After considering points made by @jcalz and @ggradnig, I realized that my use case had an additional complexity:
type Status = 'foo' | 'bar' | 'baz';
let foo = false;
const bar: Status = foo ? 'foo' : 'bar';
const foobar = {
bar
}
Interestingly, bar
does have the correct type of Status
, but foobar.bar
still has a type of 'foo' | 'bar'
.
It appears that to align with my expectations, I need to cast 'foo'
to Status
like this:
const bar = foo ? 'foo' as Status : 'bar';
With this adjustment, the typing behaves as desired and I am satisfied with it.