如何在require语句中初始化类? (打字稿)

时间:2019-04-12 10:53:42

标签: node.js typescript typescript2.0

基本类导出的外观看起来是这样的,在需要时可以这样初始化:

const api = require('myapi')('key_...');

1 个答案:

答案 0 :(得分:1)

如果我理解您的问题,那么您想在myapi模块中实例化一个类(即BasicClass)并通过默认导出的函数将其返回。在TypeScript中实现此目标的一种方法是通过以下方式:

/* The myapi module */

/* The "basic class" that will be instantiated when default export function is called */
class BasicClass {
    constructor(key:string) {
        console.log(`Constructor got key: ${key}`)
    }
}

/* The default module export is a function that accepts a key string argument */
module.exports = (key:string) => {

    /* The function returns an instance of BasicClass */
    return new BasicClass(key)
}

然后可以按如下方式使用myapi模块:

const api = require('myapi')('key_...');

/* api is instance of BasicClass */

希望有帮助