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?