如何在node.js打字稿中创建可写的全局变量 [英] How to create writable global variable in node.js typescript
问题描述
我已经声明了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屋!