Literal Inference
Literal Inference is a feature in TypeScript that allows the type of a variable or parameter to be inferred based on its value.
In the following example we can see that TypeScript considers x
a literal type as the value cannot be changed any time later, when instead y
is inferred as string as it can be modified any time later.
In the following example we can see that o.x
was inferred as a string
(and not a literal of a
) as TypeScript considers that the value can be changed any time later.
As you can see the code throws an error when passing o.x
to fn
as X is a narrower type.
We can solve this issue by using type assertion using const
or the X
type:
or: