How do I rewrite this without overload signatures, using conditional types instead?
function foo(returnString: true): string;
function foo(returnString: false): number;
function foo(returnString: boolean) {
return returnString ? String(Math.random()) : Math.random();
}
I tried the following code, but it doesn't compile without as any
:
function foo<T extends boolean>(returnString: T): T extends true ? string : number {
return (returnString ? String(Math.random()) : Math.random()) as any;
}
How can I get rid of as any
?
The error message is super-unhelpful:
Type 'string | number' is not assignable to type 'T extends true ? string : number'.
Type 'string' is not assignable to type 'T extends true ? string : number'.
any
cast or overloads are the current workarounds. Additionally in their June Design Meeting Notes they mention: Today, a type isn't assignable to a conditional type unless it's another conditional type., so it seems they are aware of this and a fix may be coming in the future. – Gutter