I am struggling to make the following code behave as expected without using:
as const
- function overloading (if impossible to achieve with arrow functions)
const f = <S extends string>(args: { str?: S }) => {
return {
a: args.str || 123,
};
};
const { a: a1 } = f({}); // expect a1's type to be 123
const { a: a2 } = f({ str: '' }); // expect a2's type to be 123
const { a: a3 } = f({ str: 'hello' }); // expect a1's type to be 'hello'
I hope for the following results:
a1
's type to be123
a2
's type to be123
a3
's type to be'hello'
However, the actual results are:
a1
's type isstring | number
a2
's type isnumber | ""
a3
's type isnumber | 'hello'
Shouldn't TypeScript automatically infer the expressions where the passed generics are used?