Typescript conditional return type with default argument value

Your overload approach should work. You can make the parameter optional for the true overload:

function myFunc(myBool?: true): string
function myFunc(myBool: false): number
function myFunc(myBool = true): string | number {
    return  myBool ? 'string' : 1
    }

myFunc()

T is not boolean, it is a subtype of boolean.

Consider a more general example:

type T0 = { foo: string; };
declare function useFoo<T extends foo>(arg: T = { foo: 'bar' });

This will fail too, because a valid T can also be { foo: string; bar: number; } (a subtype of T0), which the default argument is not assignable to.

Default arguments and generics usually don't go hand-by-hand because of this, and you're likely better off with overloading, like in Titian's answer.

Tags:

Typescript