简体   繁体   中英

Get nested type with generics

I have an object of services, each with nested requests. I'm trying to create a function to get a specific request, and want the correct type on the output.

Consider the following code:

enum Service {
  Foo = 'foo',
  Bar = 'bar'
}

const services = {
  [Service.Foo]: {
    v1: {
      getGreeting: (id: string) => 'hello',
    },
  },
  [Service.Bar]: {
    v2: {
      getInsult: () => 'idiot',
    },
  },
};

function createRequest<T extends Service>(
  serviceName: T,
  version: string,
  endpoint: string,
) {
  const service = services[serviceName] as typeof services[T];
  return service[version][endpoint];
}

const request = createRequest(Service.Foo, 'v1', 'getGreeting');

I'm nearly there but request has the type any . The function already knows the type of the service via generics, but how do I go the extra mile to get the type of the nest property being returned?

Let's create an interface for service data structure:

type ServiceType = Record<Service, Record<string, Record<string, (...args: any[]) => any>>>;

Now, in order to infer all arguments and validate them we need to make this function pure . TS likes pure functions more. We should create a function which will return another function ( curry it)

const withService = <
  ServiceObj extends ServiceType
>(services: ServiceObj) =>
  <
    Name extends keyof ServiceObj,
    Version extends keyof ServiceObj[Name],
    Endpoint extends keyof ServiceObj[Name][Version]
  >(
    serviceName: Name,
    version: Version,
    endpoint: Endpoint,
  ) => services[serviceName][version][endpoint];

Now we can test it:

const request = withService({
  [Service.Foo]: {
    v1: {
      getGreeting: (id: string) => 'hello',
    },
  },
  [Service.Bar]: {
    v2: {
      getInsult: () => 'idiot',
    },
  },
})

// (id: string) => string
const createRquest = request(Service.Foo, 'v1', 'getGreeting')

// () => string
const createRquest2 = request(Service.Bar, 'v2', 'getInsult')

const createRquest3 = request(Service.Bar, 'v22', 'getInsult') // expected error

Playground

As you might have noticed keyof ServiceObj[Name][Version] reflects function body logic

If you are interested in function argument inference, you can check my related article


Here you have a version with classes:

enum Service {
  Foo = 'foo',
  Bar = 'bar'
}

interface Base {
  [prop: `v${number}`]: Record<string, Fn>
}

class Foo {
  v1 = {
    getGreeting: (id: string) => 2,
  }
}

class Bar {
  v2 = {
    getInsult: () => 'idiot',
  }
}

type WithoutIndex = keyof Bar
const services = {
  [Service.Foo]: Foo,
  [Service.Bar]: Bar,
}

type AnyClass = new (...args: any[]) => Base
type Fn = (...args: any[]) => any


function withService<
  ServiceObj extends Record<Service, new (...args: any[]) => any>,
  >(services: ServiceObj):
  <Name extends Service,
    Version extends keyof InstanceType<ServiceObj[Name]>,
    Endpoint extends keyof InstanceType<ServiceObj[Name]>[Version]
    >(
    serviceName: Name,
    version: Version,
    endpoint: Endpoint,
    v?: keyof InstanceType<ServiceObj[Name]>
  ) => InstanceType<ServiceObj[Name]>[Version][Endpoint]
function withService<
  ServiceObj extends Record<Service, AnyClass>,
  >(services: ServiceObj) {
  return <Name extends Service,
    Version extends keyof Base,
    Endpoint extends keyof Base[Version]
  >(
    serviceName: Name,
    version: Version,
    endpoint: Endpoint,
  ) => {
    const api = new services[serviceName]();
    return api[version][endpoint];
  }
};


const request = withService({
  [Service.Foo]: Foo,
  [Service.Bar]: Bar,
})

// (id: string) => number
const createRquest = request(Service.Foo, 'v1', 'getGreeting')

// () => string
const createRquest2 = request(Service.Bar, 'v2', 'getInsult')

const createRquest3 = request(Service.Bar, 'v22', 'getInsult') // expected error

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM