How to create writable global variable in node.js typescript

烈酒焚心 提交于 2019-12-11 17:43:34

问题


I have declared a global variable

import * as io from "socket.io";

declare let SocketServer: io.Server

and tried to write in another file but this variable is read-only.

So how to make it writable?

Update

// global.d.ts 
import * as io from "socket.io";

declare global {
  let server_socket: io.Server
  let user_socket: io.Socket
}

// server.ts
import * as io from "socket.io";

console.log(server_socket)


回答1:


In TypeScript, declare blocks are used to describe your global variables. In other words, they are a way of telling TypeScript what it can expect in the global namespace — but it's your responsibility as a developer to make sure they are actually there.

The way you can create (and describe) global variables depends on the platform.

The browser (DOM)

import * as io from 'socket.io';

window.SocketServer = io.default();

declare global {
  interface Window {
    SocketServer: io.Server;
  }
}

Requires @types/socket.io. Is consumed by accessing window.SocketServer.

Node.js

import * as io from 'socket.io';

declare global {
  namespace NodeJS {
    interface Global {
      SocketServer: io.Server
    }
  }
}

global.SocketServer = io.default();

Requires @types/socket.io and @types/node. Is consumed by accessing global.SocketServer.

Universal

You can also describe a variable that is already a part of your environment and is accessible to both the client and the server.

An example of such a variable would be process — it's a part of Node.js environment, but build tools like Webpack can expose its contents to the client.

import * as io from 'socket.io';

declare global {
  var SocketServer: io.Server;
}


来源:https://stackoverflow.com/questions/53897466/how-to-create-writable-global-variable-in-node-js-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!