The following code will create a factory function in ES5:
function MyClass(val) {
if (!(this instanceof MyClass)) {
return new MyClass(val);
}
this.val = val;
}
This function can be called with or without the new
keyword:
var a = new MyClass(5);
var b = MyClass(5);
This works fine in Typescript, however I can't figure out how to create a declares file with merging that describes both behaviors. Is there a way to do this?
TypeScript defines a constructor using the constructor keyword. A constructor is a function and hence can be parameterized. The this keyword refers to the current instance of the class. Here, the parameter name and the name of the class's field are the same.
The "this" keyword always points to the object that is calling a particular method. The type of "this" in an expression depends on the location in which the reference occurs: In a constructor, member function, or member accessor, this is of the class instance type of the containing class.
So essentially, the type {} means "not required to have any properties, but may have some", and likewise the type {a: string} means "must have a property named a whose value is a string , but may have other properties too".
You can call the base class constructor from the child class by using the super() which will execute the constructor of the base class. Example: Javascript.
interface MyClass {
val: {};
}
interface MyClassConstructor {
(val: {}): MyClass;
new (val: {}): MyClass;
}
declare const MyClass: MyClassConstructor;
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