【问题标题】:How to initialise class in the require statement? (typescript)如何在require语句中初始化类? (打字稿)
【发布时间】:2019-04-12 19:39:51
【问题描述】:

一个基本的类导出需要看起来像这样,当需要时,它可以像这样初始化:

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

【问题讨论】:

    标签: node.js typescript typescript2.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 */
    

    希望有帮助

    【讨论】:

    • 得到 TypeError: require(...) is not a function
    • 我想重点是把它放在一个语句上......这似乎有效: const api = (key: string) => { return new BasicClass(key) } module.exports = api ;
    • 是的,这也是一个选项 - 您可以通过直接在 module.exports 上定义箭头函数来稍微压缩 myapi 模块,如更新的答案所示
    • 谢谢! (我添加了一个返回类型,所以我也可以获得 IntelliSense,但其他都很棒)
    • 在这里利用 OP :) 但是如果 BasicClass 的参数基本上是从另一个文件中导入某些函数,我该如何使用外部文件中的密钥 (jsfiddle.net/rdspqek1)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-18
    • 2021-08-15
    • 2018-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多