I ran into a problem with type inference, and tried to create the smallest reproducible example possible
type Options = { value: 'a' | 'b' }
const getOption = (): Options => {
const result = { value: 'a' };
return result;
}
Error
Type '{ value: string; }' is not assignable to type 'Options'.
__ Types of property 'value' are incompatible.
____ Type 'string' is not assignable to type '"a" | "b"'
(I'm not asking for a solution. I want to know why why TypeScript can't infer this)
I can return the result in a single operation without the error. I assume TypeScript is inferring the result variable to be of the type { value: string } instead of { value: 'a' }
To fix it I can change the result line to cast the string value to the literal it actually is, but it seems beyond silly.....
const result = { value: ('a' as 'a') };
Question
How come this is necessary? I'm usually always impressed about the depth of TypeScript's type inference, but for some reason it is struggling with this simple problem
return { value: 'a' }works fine: Playground Link I guess the check through reference for object not being changed is expensive for the TS compiler, hence it's not performed. You can also sayconst result = { value: 'a' } as const;orconst result: Options = { value: 'a' };but seems a bit redundant.resultvariable like this:const result: Options = { value: 'a' };.