I have two definitions that are exactly the same, however I would like it if the first one returned Promise<Cursor<T>> when the value of limit is greater than 1, and second one should returned Promise<T> if the value of limit is 1 how would I define this, is it possible to define or is there another way to define it?
public async select<T extends any>(limit: number): Promise<Cursor<T>>
public async select<T extends any>(limit: number): limit is 1 && Promise<T>
public async select<T extends any>(...args: any[]): Promise<T | Cursor<T>> {
// Do query and return the Pomise
}
You can use a numeric literal type in your overload to get the desired effect:
class Cursor<T>{}
class O {
public async select<T extends any>(limit: 1): Promise<T>
public async select<T extends any>(limit: number): Promise<Cursor<T>>
public async select<T extends any>(...args: any[]): Promise<T | Cursor<T>> {
return null as any
}
}
let o = new O();
let s = o.select(1) // Promise<{}>
let m = o.select(2) // Promise<Cursor<{}>>
This will however only work if you pass the constant 1 to the function, and might cause more confusion then it's worth.
let n = 1;
o.select(n);// n is a number so it's types as a Promise<Cursor<{}>>
const constOne = 1;
o.select(constOne);// Promise<{}>
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