0
我正在用TypeScript重寫一箇舊的NPM模塊,並且遇到了一個有趣的問題。如何在TypeScript中動態地將Class方法導出爲獨立函數?
的模塊,在其目前的狀態,看起來是這樣的 -
1.1我-module.js
export function init(options) {
//initialize module
}
export function doStuff(params) {
//do stuff with options and other things
}
1.2example.js
var m = require('my-module');
m.init({thing: 'doodad'});
m.doStuff('bwoah');
我是在TS(目標ES6)重寫本,並計劃寫的模塊,可以採取一個構造函數(代替init()
)一類的,讓我寫得真好之類的東西 -
1.3例如,new.js
import {Thing} from 'my-module';
const aThing1 = new Thing({thing: 'doodad'});
const aThing2 = new Thing();
aThing2.init({thing: 'doodad'});
aThing1.doStuff('bwoah');
aThing2.doStuff('bwoah');
// If I can do at least one of aThing1 or aThing2, I can die a happy man.
重寫的打字稿模塊看起來是這樣的 -
1.4我模塊,new.js
class Thing {
options: Object;
constructor(options: Object) {
this.options = options;
}
init(options: Object) {
this.options = options;
return this;
}
doStuff(thingForStuff: string) {
// ...
}
}
我想達成什麼
我希望保持與舊的API完全向後兼容,以及。所以理想情況下,我應該可以做1.2和1.3。
什麼我試過到目前爲止
export
荷蘭國際集團的Thing
類;這讓我做1.3,但不是1.2。export
ing單身人士,與export default new Thing()
;這讓我做1.3,但不是1.2。寫這樣的事情 -
export class Thing { options: Object; constructor(options: Object) { this.options = options; } init(options: Object) { this.options = options; return this; } doStuff(thingForStuff: string) { // ... } } const singleThing = new Thing(); export function init(options) { return singleThing.init(options); } export function doStuff(string) { return singleThing.doStuff(string); }
這既1.2和1.3效果很好 - 但是這似乎有些單調乏味,基本複製每個功能。
當然,必須有一個更優雅的方式來做到這一點?