Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript conditional return type with default argument value

Tags:

typescript

I'm trying to make a function return a conditional type based on the argument value but with a default value for the argument :

function myFunc<T extends boolean>(myBoolean: T = true): T extends true 
       ? string 
       : number {
       return  myBoolean ? 'string' : 1
    }

this throws an error Type 'true' is not assignable to type 'T'. 'true' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'boolean'.

I don't understand this error, since T is a boolean how come I can't assign true to it ?

I tried another approach with function overloads :

function myFunc(myBool: true): string
function myFunc(myBool: false): number
function myFunc(myBool = true) {
       return  myBool ? 'string' : 1
    }

myFunc()

but now typescript won't let me call myFunc() with no argument (even though it has a default value) and the first overload has an error This overload signature is not compatible with its implementation signature.

Is it even possible to do what I'm trying to achieve here in typescript and if son how ?

like image 531
Lakston Avatar asked Jul 16 '19 12:07

Lakston


People also ask

Can a type have a default value TypeScript?

In TypeScript, there is not currently a way to supply a default value to a parameter with a generic type. The following code throws an error: Type 'number' is not assignable to type 'T'.

What is default parameter in TypeScript?

The default parameter in TypeScript is used to assign some default value to the variable. In JavaScript, we have this provision not to pass the required argument to the called function because it internally manages, But in TypeScript, we cannot do this.

What are conditional Types 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 is default value of number in TypeScript?

The default value means the value of a variable that is defined, but not assigned. Like let a : number; . This happens a lot in object definitions.


1 Answers

Your overload approach should work. You can make the parameter optional for the true overload:

function myFunc(myBool?: true): string
function myFunc(myBool: false): number
function myFunc(myBool = true): string | number {
    return  myBool ? 'string' : 1
    }

myFunc()
like image 73
Titian Cernicova-Dragomir Avatar answered Oct 06 '22 19:10

Titian Cernicova-Dragomir