在打字稿中定义不使用class关键字的类

问题描述:

我是一个TypeScript新手,以下是大多数好奇心的问题。在打字稿中定义不使用class关键字的类

在ES6之前,JavaScript没有类。因此,我希望能够脱离在TypeScript中的使用。

但是,我没有找到正确的做法。把这个样品等级:

class FooConcrete { 
    getImpl :() => number; 

    constructor(getImpl:() => number) { 
     this.getImpl = getImpl; 
    } 

    get() : number { 
     return this.getImpl(); 
    } 
} 

由于类型定义文件通常暴露类似于下面的东西,我开始与:

interface FooConcrete 
{ 
    get() : number; 
} 

interface FooConcreteStatic 
{ 
    new() : FooConcrete; 
} 

但我怎么然后定义构造函数FooConcrete

我想:

var FooConcrete : FooConcreteStatic = function FooConcrete() { 
    return { 
     get:() => 42 
    }; 
}; 

这可能没有什么编译,但相应的JavaScript按预期工作:

new FooConcrete().get() // => 42 

是否有申报FooConcrete作为FooConcreteStatic的方式,而无需编写它作为类?

(在落后的情况下动机是,我很好奇,想看看是否有办法从原型的get到实现getImpl类摆脱虚假重定向的 - 在这种情况下没有必要为get在原型中。)

我敢肯定,你不能这样做,而不欺骗编译器,因为如果你使用类,语言为你工作。

您的打字稿类代码:

class FooConcrete { 
    getImpl :() => number; 

    constructor(getImpl:() => number) { 
     this.getImpl = getImpl; 
    } 

    get() : number { 
     return this.getImpl(); 
    } 
} 

目标ES5当编译成这样:

var FooConcrete = (function() { 
    function FooConcrete(getImpl) { 
     this.getImpl = getImpl; 
    } 
    FooConcrete.prototype.get = function() { 
     return this.getImpl(); 
    }; 
    return FooConcrete; 
}()); 

而且定义文件:

declare class FooConcrete { 
    getImpl:() => number; 
    constructor(getImpl:() => number); 
    get(): number; 
} 

JS的输出几乎是你想要做的(只是原型是“正确的”路径),并且定义使用declare class,而不是像你指出的那样使用接口。

这种方法可以产生更清晰的代码并将其编译成es5类或es6类。