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 ?
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'.
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.
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).
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With