The following function was largely lifted from the typescript handbook section on using conditional types, yet it doesn't work:
function test<T extends boolean>(a: T): T extends true ? string : number {
return a ? '1' : 1
}
Typescript is reporting that:
Type '1 | "1"' is not assignable to type 'T extends true ? string : number'.
Type '1' is not assignable to type 'T extends true ? string : number'.
I imagine I'm missing something obvious. How can I construct this function so that typescript correctly infers the type based on the function's argument?
I realize that this specific problem could be solved using function signature overloading, but I'd like to learn more about conditional types.
The short a answer is you can't. No value will be assignable to an unresolved conditional type (a conditional type that still depends on a free generic type variable). The only thing you can do is use a type assertion.
function test<T extends boolean>(a: T): T extends true ? string : number {
return (a ? '1' : 1) as any
}
Conditional types are useful to express relations between parameters but they don't help when it comes to implementing the function. Another approach would be to use a more permissive implementation signature.
function test<T extends boolean>(a: T): T extends true ? string : number
function test(a: boolean): number | string {
return (a ? '1' : 1)
}