I have the following code which won't compile with TypeScript compiler 3.7.3
type Fruit = 'apple' | 'banana'
const val = 'apple'
// Works. TS remembers the value of `val`
const fruit: Fruit = val
type Basket = {
fruit: Fruit
}
const obj = {
fruit: 'apple'
}
// Error: Type 'string' is not assignable to type 'Fruit'.
// TS probably discarded that `fruit` property has concrete value and treats it as any `string`.
const structuralBasket: Basket = obj
// This works
const declaredBasket: Basket = {
fruit: 'apple'
}
I need the obj to stay as is. What I cannot do and not looking for in the answer:
- using enums
- declaring
objas aBasket
Is this a limitation of TypeScript compiler?
If so, is there workaround ? Will this be addressed in the future ?
fruitinobjwill be something that's contained inFruitby doingobj = { fruit: 'apple' as const }. I'm not if you can somehow automatically enable this sort of inference in the compiler, though - the fact that you've declaredfruitto be'apple'now doesn't mean it can't change later if somebody doesobj.fruit = 'lemon'.