基本类导出的外观看起来是这样的,在需要时可以这样初始化:
const api = require('myapi')('key_...');
答案 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 */
希望有帮助