打字稿:如何在NodeJS中扩展全局对象?

时间:2019-12-28 01:39:45

标签: typescript

我试图像global.spotConfig一样在NodeJS中扩展Global对象。我一直在寻找答案,但没有人适合

请帮助我,我的代码是here

注意:如果服务器控制面板未运行,请重新启动服务器

1 个答案:

答案 0 :(得分:1)

请参见https://stackoverflow.com/a/35074833/1937643

您要的是:

var http = require("http");

declare module NodeJS {
    interface Global {
        spotConfig: string
    }
}

//create a server object:
http
    .createServer(function (req, res) {
        // assign a new value to the global property
        global.spotConfig = "anything";
        console.log(global.spotConfig);
        // error TS2339: Property 'config' does not exist on type 'Global'.
        res.write("Hello World!"); //write a response to the client
        res.end(); //end the response
    })
    .listen(8080); //the server object listens on port 8080