0

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)

enter image description here

WasiF
  • 26,101
  • 16
  • 120
  • 128
  • "and tried to write in another file"... can you elaborate? `declare` only 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 instantiate `SocketServer`, you'd still need to do `new io.SocketServer(...)`. Or assign `io.SocketServer` to your `SocketServer` – pushkin Dec 23 '18 at 17:28

1 Answers1

2

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;
}
Karol Majewski
  • 23,596
  • 8
  • 44
  • 53
  • You still need to import `import * as io from "socket.io"` in order to use it. – Karol Majewski Dec 23 '18 at 14:35
  • I thought you had already created your global variable and were looking only for a way to tell TypeScript about it. I updated my answer to cover how both can be done. – Karol Majewski Dec 23 '18 at 18:42
  • Actually I am developing a `MEAN` app. `Angular7` & `REST Api` depends on same configuration files created by `Angular`. Getting error like Property 'SocketServer' does not exist on type 'Global'. – WasiF Dec 24 '18 at 01:17