Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

Create an async function that returns type according to a boolean param

$
0
0

I was trying to create an asynchronous function in TypeScript with proper types return. The function would have a boolean parameter that determines the return type of the function. I searched on the internet and it seems that using type conditional is the way to go.

I implemented the code more or less like in the following:

type Foo = {    propA: string    propB: string}type Bar = Omit<Foo, 'propB'> & {propC: string}type ConditionalFooBar<T extends boolean> = T extends true? Foo:Barasync function mainFunction<T extends boolean>(param:T) : Promise<ConditionalFooBar<T>>{    // Some function awaits happened here    if(param===true){        return {            propA: "a string",            propB: "a string"        }    }    return {        propA: "a string",        propC: "a string"    }}

With this code, the TypeScript compiler complained the following at the first return statement:

Type '{ propA: string; propB: string; }' is not assignable to type 'ConditionalFooBar<T>'.ts(2322)

How do I resolve this?


Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>