K. D.
K. D.

Reputation: 4239

TypeScript: Type Mapping resolver object to result types

If I have an interface like this:

interface GetDomainInfoResolver {
  getDomainInfo: (domain: string) => Promise<DomainInfoType>
}

How can I create a Mapped type that results in an interface/type like this:

interface GetDomainInfoService {
  getDomainInfo: DomainInfoType
}

So that I can use it like this:

type GetDomainInfoService = Transform<GetDomainInfoResolver>

Is this possible at all?

The background is that I want to create a type interface between my GraphQL server resolvers (TypeGraphQL) and my client (@apollo/react-hooks).

Thank you very much.

Upvotes: 1

Views: 158

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250106

You can use a mapped type to map over the properties and get the return type (using ReturnType<T[P]>) with a conditional type to extract the promise value type:

interface GetDomainInfoResolver {
  getDomainInfo: (domain: string) => Promise<DomainInfoType>
}

type GetAllResults<T extends Record<keyof T, (...a: any[]) => any>> = {
    [P in keyof T]: ReturnType<T[P]> extends Promise<infer U> ? U : never
}

type GetDomainInfoService = GetAllResults<GetDomainInfoResolver>
// Same as
// type GetDomainInfoService = {
//     getDomainInfo: DomainInfoType;
// }

Playground Link

Upvotes: 3

Related Questions