Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript conditional return value type?

Tags:

function f(x:boolean|string) { return x } f(true) // boolean | string 

Why can't typescript understand that the return value is a boolean?

function f(x:boolean|string) {     return typeof x === 'boolean' ? true : 'str' } f(true) // boolean | string 

It can't understand this either.

Do I need to manually setup a function overload definition?

like image 386
Farzher Avatar asked Feb 15 '18 13:02

Farzher


People also ask

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).

What does ?: Mean in TypeScript?

What does ?: mean in TypeScript? Using a question mark followed by a colon ( ?: ) means a property is optional. That said, a property can either have a value based on the type defined or its value can be undefined .

How do you check TypeScript type?

Use the typeof operator to check the type of a variable in TypeScript, e.g. if (typeof myVar === 'string') {} . The typeof operator returns a string that indicates the type of the value and can be used as a type guard in TypeScript.

What is type Never in TypeScript?

TypeScript introduced a new type never , which indicates the values that will never occur. The never type is used when you are sure that something is never going to occur. For example, you write a function which will not return to its end point or always throws an exception.


1 Answers

Typescript will not infer different return types based on type guards in the function. You can however define multiple function signatures for let the compiler know the links between input parameter types and result type:

function ff(x: boolean): boolean; function ff(x: string): string;  // Implementation signature, not publicly visible function ff(x: boolean | string): boolean | string {     return typeof x === 'boolean' ? true : 'str' } 
like image 66
Titian Cernicova-Dragomir Avatar answered Oct 26 '22 07:10

Titian Cernicova-Dragomir