I encountered an issue while utilizing generic overload functions, as demonstrated below in the playground.
The generic type T1
is solely used in the return type and not the parameters. Therefore, when attempting to use overload #2, I am required to specify all the types like f<string, string>('123')
, which can sometimes be impractical. Is there a way to make f<string>('123')
match overload #2
?
function f<T1, T2>(t2: T2): T1
function f<T1>(): T1
function f<T1, T2>(t2?: T2): T1 | void {
}
f<string, string>('123') // works fine
f<string>() // works fine
f<string>('123') // error occurs here, is there a way to avoid using f<string, string>('123') ?
function f<T1, T2>(t2: T2): T1
function f<T1>(): T1
function f<T1, T2>(t2?: T2): T1 | void {
}
f < string, {id: number}>({id: 123}) // works fine
f<string>() // works fine
f<string>({id:123}) // TypeScript raises an issue here, can we address it without using f<string, string>({id:123}) ?