When it comes to generically typed parameters in TypeScript, there are no magic tricks (at least not yet). This results in the type of getIndex ? 1 : ''
being string | number
, rather than B extends true ? number : string
. As a consequence, this mismatch with the function's return type leads to an error.
One approach to address this issue is by utilizing overloads:
function handleTab(getIndex?: false): string
function handleTab(getIndex: true): number;
function handleTab(getIndex?: boolean): string | number;
function handleTab(getIndex?: boolean): string | number {
return getIndex ? 1 : '';
}
An additional handleTab(getIndex?: boolean)
ensures correct functionality even when passing a parameter of type boolean
.
Alternatively, you can consolidate the signatures into one using overloads:
function handleTab<B extends boolean = false>(getIndex?: B): B extends true ? number : string;
function handleTab(getIndex?: boolean): string | number {
return getIndex ? 1 : '';
}
However, both of these examples don't verify if the returned expression aligns with the provided overloads. For instance, returning just 1
would not trigger any complaints.
Try it out on TypeScript Playground