Exporting a class constructor as a named function using TypeScript

时间:2017-08-04 12:55:30

标签: typescript constructor module

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?

1 个答案:

答案 0 :(得分:0)

首先,是的,你可以使用下面的东西来做到这一点:

export const DoSomething = DoSomethingClass.prototype.constructor;

这将避免您可能面临的编译错误。

但是,等等......

我个人的意见是避免这种构造。

问题是你的用例到底是做什么的。如果您只想执行在构造函数中编写的代码,那么它可能会满足您的需求。在这种情况下,一个明智的选择是改为导出function

但是,当使用构造函数时,通常的情况是实例化给定类的对象。这样做是使用new operator

请参阅以下示例,其中var1未定义,其中new未使用,var2不是这种情况。请注意,虽然示例是在JavaScript中,但在编译之后,TypeScript也将转换为非常相似的东西。

&#13;
&#13;
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
&#13;
&#13;
&#13;

似乎这不是你要找的答案,但我希望这会有所帮助。

其他好的读物:

  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