I'm trying to write a declaration file for a library we're using without any means to modify it.
The way it works is that you can send a configuration object, the return will be based on some keys inside of it
const args = {
// ...
resources: {
One: {
query: { url: 'value' }
}
}
}
library(args)
Invoking it returns an object with the deeply nested keys of resources
as functions
const ret = {
One: {
query: async (query) => <data>
}
}
// ret.One.query(args) => data
Ideally each <data>
would also be typed, I'm not sure if this is possible due to the dynamic keys? I've tried a couple of approaches using keyof
the parameters without any luck
Edit: Updated example
const config = {
// ...
resources: {
User: {
find: { url: 'http://example.com/userapi' }
},
Dashboard: {
update: { method: 'post', url: 'http://example.com/dashboardapi'}
}
}
}
const services = serviceCreator(config)
// service creator turns the supplied resources object into promise functions
await services.User.find({id: '123'}) // Promise<User>
await services.Dashboard.update({user: '123', action: 'save'}) // Promise<Dashboard>
Without further information, I'm guessing that you're looking for something like this:
type Arg<T> = { resources: T; }
type Ret<T> = {
[K in keyof T]: {
query: (...query: any[]) => Promise<any>;
}
}
declare const library: <T>(arg: Arg<T>) => Ret<T>;
Let's test it to see if it works:
const args = {
resources: {
One: {
query: { url: 'value' }
}
}
}
var ret = library(args);
async function test() {
await ret.One.query(); // OK
}
You can try it in this playground.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments