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

1
  • "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 Commented Dec 23, 2018 at 17:28

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

You still need to import import * as io from "socket.io" in order to use it.
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.
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'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.