javascript - 如何在 TypeScript 中将类方法动态导出为独立函数?

标签 javascript node.js typescript

我正在用 TypeScript 重写一个旧的 NPM 模块,并且遇到了一个有趣的问题。

该模块在当前状态下看起来像这样 -

1.1 my-module.js

export function init(options) {
    //initialize module
}

export function doStuff(params) {
    //do stuff with options and other things
}

1.2 example.js

var m = require('my-module');
m.init({thing: 'doodad'});
m.doStuff('bwoah');

我正在 TS 中重写它(针对 ES6),并计划将模块编写为可以采用构造函数的类(代替 init()),让我可以编写一些不错的东西,例如 -

1.3 example-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.

重写后的 TypeScript 模块如下所示 -

1.4 my-module-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

到目前为止我已经尝试过

  1. 导出Thing类;这让我可以执行 1.3,但不能执行 1.2。
  2. 导出单例,使用export default new Thing();这让我可以执行 1.3,但不能执行 1.2。
  3. 写这样的东西 -

    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 都很有效 - 但是基本上重复每个函数似乎很乏味。

肯定有一种更优雅的方法来做到这一点吗?

最佳答案

是的,我们可以! © 在“Thing”文件中结合默认导出导出:

export class Thing {
    init() { }
}

export default new Thing();

关于javascript - 如何在 TypeScript 中将类方法动态导出为独立函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43246331/

相关文章:

javascript - 如何使用 @Param 从路由中检索 URL

jenkins - 如何在 Jenkins 中为 sonarqube 配置 TSLint 插件?

javascript - 代码镜像2 : How to format a pasted content?

javascript - 使用 webpack 和 babel-loader 的 ES6 模块导入导出

javascript - NodeJS,不关闭mysql连接

node.js - 云存储时 `node_modules`目录如何处理?

javascript - 如何使用 JavaScript + jQuery 确保 URL 是图像?

javascript - 如何使用 jQuery 设置 HTML 表格 <td> 内的选择控件的 id 和名称?

javascript - 使用 promises 从 mongo db 检索对象时出错

mysql - 如何在 Typescript 项目中使用 express-mysql-session?