Inferring the ReturnType<> of a chained function

90 Views Asked by At

I'm working with the twilio-node pkg and there's the fetch function:

lookupResponse = await twilioClient.lookups.v1.phoneNumbers('+123').fetch({type: 'carrier'});

with a clearly defined return type, Promise<PhoneNumberInstance>. Since I'm initializing the lookupResponse beforehand, I'd like to extract / infer the function's return type straightaway.

Now, I already know how to unwrap a promise's type:

export type ThenArg<T> = T extends PromiseLike<infer U> ? U : T;

But how do I specify the argument of the previously chained phoneNumbers function? Trying this:

let lookupResponse: ThenArg<
  ReturnType<typeof twilioClient.lookups.v1.phoneNumbers.fetch>
>;

throws Property 'fetch' does not exist on type 'PhoneNumberListInstance'.

What do I need to pass here?

let lookupResponse: ThenArg<
   ReturnType<typeof twilioClient.lookups.v1.phoneNumbers.???.fetch>
//                                                        ^^^            
>;
1

There are 1 best solutions below

1
On BEST ANSWER

I know nothing about Twilio so apologies in advance if I steer you the wrong way, but based on your code, phoneNumbers is a function, not just a property. So you need the return type of the fetch function that's on the return type of twilioClient.lookups.v1.phoneNumbers. Something like:

type LookupResponseType = ThenArg<
    ReturnType<
        ReturnType<
            typeof twilioClient["lookups"]["v1"]["phoneNumbers"]
        >["fetch"]
    >
>;

Playground link with mockup