I have some code that can either return a boolean or a Promise depending on the parameters provided.
function setGuid<B extends boolean>(guid: string, shouldValidate?: B): B extends true ? boolean : Promise<boolean>
function setGuid(guid: string, shouldValidate?: boolean): boolean | Promise<boolean> {
if (shouldValidate){
return true
}
return Promise.resolve(true);
}
This functionality is working as expected. When I call setGuid("*", false)
, it correctly identifies the return type as Promise<boolean>
. Similarly, when I call setGuid("*", true)
, TypeScript recognizes the return type as a boolean
.
However, the challenge lies in setting a default return type. I want TypeScript to understand that if the shouldValidate
parameter is not provided, the return type should default to Promise<boolean>
. Currently, if I omit the second parameter, TypeScript assumes that boolean | Promise<boolean>
is being returned.
When I try calling setGuid("*")
, I encounter the error message:
Property 'then' does not exist on type 'boolean | Promise<boolean>'. Property 'then' does not exist on type 'false'.
I would greatly appreciate any assistance with resolving this issue. Thank you!