How can I create a .d.ts file that represents the following JavaScript API?
Loaderis a class which is not exported globallyloaderis exported globally, and is an instance ofLoaderloader.Loaderis theLoaderclass itselfLoaderhas a static methodcreate, which creates an instance ofLoader
So essentially loader behaves like a namespace that includes the class Loader, but is also a instance of Loader. The following doesn't work, because TypeScript won't merge a namespace with a value:
declare namespace loader {
class Loader {
id: number;
name: string;
load(url: string): any;
static create(name: string, parent?: Loader): Loader;
}
}
// This doesn't work, because a namespace cannot be merged with a value:
declare const loader: loader.Loader;
Using this API from JavaScript looks like this:
// Call load() on the default Loader instance
loader.load('/foo/index');
// loader.Loader is a class, and loader is an instance of it
if(loader instanceof loader.Loader) {
console.log('Yes, loader is a Loader');
}
// Create a new Loader instance
var myLoader = loader.Loader.create('my-loader');
// Call load on this Loader instance
myLoader.load('/bar/something');
// myLoader is also an instance loader.Loader
if(myLoader instanceof loader.Loader) {
console.log('Yes, myLoader is a Loader');
}