Get Off My Lawn
Get Off My Lawn

Reputation: 36289

Define return type when parameter is a certain value

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
}

Upvotes: 3

Views: 54

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249466

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<{}>

Upvotes: 2

Related Questions