简体   繁体   中英

Exporting a class constructor as a named function using TypeScript

Suppose I have this class:

export class DoSomethingClass<TEntity> {
    constructor(entity: TEntity) {
    }
}

I can call it like this from other code:

new DoSomethingClass<Person>(myPersonObject);

I would like to achieve the following shorthand syntax:

DoSomething<Person>(myPersonObject);

Which I can do with something like:

export function DoSomething<TEntity>(entity: TEntity): DoSomethingClass<TEntity>{
    return new DoSomethingClass<TEntity>(entity);
}

But of course this involves a lot of duplication. Ideally I would like:

export DoSomething = DoSomethingClass.prototype.constructor;

But this doesn't work, otherwise I wouldn't be asking :)

Is there a non-duplication way of exporting the constructor of a class as an individual, named, short-hand function?

First thing is that yes you can do it using something like below:

export const DoSomething = DoSomethingClass.prototype.constructor;

This will avoid the compilation error that you are probably facing.

However, wait...

My personal opinion is to avoid such construct.

The question is what exactly your use case is for doing it. If you just want to execute the code written in constructor, then it might serve your purpose. In that case a sensible alternative is to export a function instead.

But, when a constructor is used the usual case is to instantiate an object of the given class. And to do so is to use the new operator .

Refer the below example, where var1 is undefined where new is not used, which is not the case for var2 . Note that though the example is in JavaScript, but after compilation, TypeScript will also be converted to something very similar.

 var myFunction = function(prop1) { this.prop1 = prop1; console.log("myFunction called. prop1:" + this.prop1); this.method1 = function() { console.log("Method1") } } var var1 = myFunction("called as normal func"); var var2 = new myFunction("called with new"); console.log(var1); //undefined console.log(var2); // var1.method1(); //error var2.method1(); console.log(var2.__proto__ === myFunction.prototype); //true 

Seems that it is not the answer you were looking for, but I hope this helps.

Additional good reads:

  1. https://basarat.gitbooks.io/typescript/content/docs/classes-emit.html
  2. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/proto

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM