Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: conditional types and using a boolean parameter to control the return type

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'.
like image 508
thorn0 Avatar asked Jul 19 '18 21:07

thorn0


People also ask

How do I return a boolean in TypeScript?

To add boolean type to function return value first, declare the function, then add a : symbol (colon) after the parameters opening and closing brackets () and then type the word boolean to indicate that the function's return value is of boolean type.

What are conditional types in TypeScript?

Conditional types help describe the relation between the types of inputs and outputs. When the type on the left of the extends is assignable to the one on the right, then you'll get the type in the first branch (the “true” branch); otherwise you'll get the type in the latter branch (the “false” branch).

How do you use boolean in TypeScript?

TypeScript treats it like an object type. So, instead of using upper case function checkExistence(b: Boolean) , use the lower case function checkExistence(b: boolean) boolean type.

Does TypeScript have boolean?

The boolean is a primitive type in Typescript. It represents a simple true/false value. They are implemented as numerical values with a single binary digit (i.e., 0 & 1). The Boolean is an object wrapper for the primitive boolean value.


1 Answers

I'm not exactly sure why the compiler can't accept this as is (not extremely familiar with TypeScript), but here's what you could do:

function foo<T extends boolean>(returnString: T): T extends true ? string : number;
function foo<T extends boolean>(returnString: T): string | number {
  return returnString ? String(Math.random()) : Math.random();
}

Basically you separate the declaration (public signature) and the implementation, giving the more accurate signature to the declaration and the broader one to the implementation.

like image 108
Jeto Avatar answered Nov 15 '22 18:11

Jeto