I needed to create an asynchronous function in TypeScript with proper type return. The challenge was to have a boolean parameter that determines the return type of the function. After some research online, I found that using type conditional is the recommended approach.
I wrote the code as follows:
type Foo = {
propA: string
propB: string
}
type Bar = Omit<Foo, 'propB'> & {propC: string}
type ConditionalFooBar<T extends boolean> = T extends true? Foo:Bar
async function mainFunction<T extends boolean>(param:T) : Promise<ConditionalFooBar<T>>{
// Some async operations here
if(param===true){
return {
propA: "a string",
propB: "a string"
}
}
return {
propA: "a string",
propC: "a string"
}
}
However, when I tried to compile this code, TypeScript threw an error at the first return statement:
Type '{ propA: string; propB: string; }' is not assignable to type 'ConditionalFooBar<T>'.ts(2322)
How can I fix this issue?