Get nested type with generics
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