如何在node.js打字稿中创建可写的全局变量 [英] How to create writable global variable in node.js typescript

查看:135
本文介绍了如何在node.js打字稿中创建可写的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经声明了global变量

import * as io from "socket.io";

declare let SocketServer: io.Server

并尝试写入另一个文件,但是此变量是只读的.

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

那么如何使其可写?

更新

// 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)

推荐答案

在TypeScript中,declare块用于描述您的全局变量.换句话说,它们是一种告诉TypeScript在全局命名空间中可以期望什么的方式,但是作为开发人员,您有责任确保它们确实在其中.

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.

浏览器(DOM)

import * as io from 'socket.io';

window.SocketServer = io.default();

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

需要@types/socket.io.通过访问window.SocketServer被消耗.

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();

需要@types/socket.io@types/node.通过访问global.SocketServer被消耗.

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

通用

您还可以描述一个变量,该变量已经是您环境的一部分,并且客户端和服务器均可访问.

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

这样的变量的一个例子是process-它是Node.js环境的一部分,但是Webpack之类的构建工具可以将其内容公开给客户端.

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;
}

这篇关于如何在node.js打字稿中创建可写的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆