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:
let foo = false;
const bar = foo ? 'foo' : 'bar';
const foobar = {
bar
}
bar
is correctly typed as 'foo' | 'bar'
:
But foobar.bar
gets typed as string
:
Just curious why.
Update
So @jcalz and @ggradnig do make good points. But then I realized my use case had an extra twist:
type Status = 'foo' | 'bar' | 'baz';
let foo = false;
const bar: Status = foo ? 'foo' : 'bar';
const foobar = {
bar
}
Interestingly, bar
does have a type of Status
. However foobar.bar
has a type of 'foo' | 'bar'
still.
It seems that the only way to make it behave how I was expecting is to cast 'foo'
to Status
like:
const bar = foo ? 'foo' as Status : 'bar';
In that case, the typing does work properly. I am OK with that.
See Question&Answers more detail:os