Reputation: 331
I'm working on a loader class for Typescript that loads from an external library based on string addresses.
Example: 'namespace/subnamespace/module'
or 'namespace/module'
I'd like my loader class to return an interface for each requested module so that the proper typing is automatic where the loader class is used.
Example:
export abstract class moduleLoader {
public static load(...modules: string[]) {
return externalLoader.loadModules(modules); // Promise<any[]>
}
}
------------------------------
let [module1, module2] = await moduleLoader.load('namespace/subnamespace/module', 'namespace/module');
if (module1 instanceof iNamespace.iSubnamespace.iModule) { }
I can't figure out how to construct the loader method in such a way as to either infer or map the interface from the string passed in, or pass in the interface and get a string from there to pass to the external loader.
I know I can set a generic on the load method to have the return value given the proper interface, but I'd like it to be automatic so that the developers using the method don't need to figure it out themselves and to eliminate runtime errors. This codebase is for use by outside devs, so I don't want to trust that they know what they're doing.
Is this even possible?
Any help or thoughts are appreciated.
Upvotes: 4
Views: 58
Reputation: 23692
It's not exactly what you need but you could use function overloads to provide one library at a time:
interface MyLib1 {
str: string
}
interface MyLib2 {
nb: number
}
function load(libName: "MyLib1"): Promise<MyLib1>
function load(libName: "MyLib2"): Promise<MyLib2>
function load(libName: string): Promise<any> {
return /* */
}
Then, use it:
let myLib1 = await load("MyLib1") // type is: 'MyLib1'
let myLib2 = await load("MyLib2") // type is: 'MyLib2'
Or, use it to simultaneously load several libraries:
let [myLib1, myLib2] = await Promise.all([
load("MyLib1"),
load("MyLib2")
])
// 'myLib1' is of type 'MyLib1', and 'myLib2' is of type 'MyLib2'
Upvotes: 1