Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factory function in a Typescript declares file, with and without the new keyword

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?

like image 417
Andrew Avatar asked Feb 07 '17 16:02

Andrew


People also ask

Which keyword is used to define class in TypeScript?

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.

How do I use this keyword in TypeScript?

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.

What does {} mean in TypeScript?

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".

How do you call a constructor from a class in TypeScript?

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.


1 Answers

interface MyClass {
  val: {};     
}

interface MyClassConstructor {
  (val: {}): MyClass;
  new (val: {}): MyClass;
}

declare const MyClass: MyClassConstructor;
like image 109
Aluan Haddad Avatar answered Oct 02 '22 00:10

Aluan Haddad