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;
}
declareonly tells TypeScript that the variable exists somewhere, it's not actually creating the variable for you, which is why you get the crash below. If you want to instantiateSocketServer, you'd still need to donew io.SocketServer(...). Or assignio.SocketServerto yourSocketServer