I'm writing a TypeScript declaration file for a JavaScript game engine with a global structure and I don't quite know how to deal with this function that returns a class constructor. Here is a simplified version of the code:
var createScript = function(name) {
var script = function(args) {
this.app = args.app;
this.entity = args.entity;
}
script._name = name
return script;
}
Users are meant to extend the script class constructor with their own code like this:
var MyScript = createScript('myScript');
MyScript.someVar = 6;
MyScript.prototype.update = function(dt) {
// Game programming stuff
}
What is the proper way to deal with the createScript function and script class constructor in my declaration file?
UPDATE I have updated my code example to show that users are also expected to extend the static side of the "class". The answers given so far, though awesome, don't seem to allow for that.
you can declare the returntype of createScript as some kind of generic script constructor
interface AbstractScript {
app;
entity;
}
interface ScriptConstructor<T extends AbstractScript> {
new(args: AbstractScript): T;
readonly prototype: T;
}
declare function createScript(name: string): ScriptConstructor<any>;
and then
interface Foo extends AbstractScript {
foo(): void;
}
let Foo:ScriptConstructor<Foo> = createScript("Foo");
Foo.prototype.foo = function () { }
let d = new Foo({app: "foo", entity: "bar"});
d.foo();
d.entity
d.app
Note: named the constructor and the interface of the created class both Foo for conveniance reasons.
Thaught first, TS might have an issue with that, but no, it differentiates nicely.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With