Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use socket.IO client type definitions for Typescript?

I have installed the Typescript definitions for a SocketIO client using

npm install @types/socket.io-client

But in VS Code I still get type errors:

let socket: SocketIOClientStatic = io() 

Type 'Socket' is missing the following properties from type 'SocketIOClientStatic': protocol, Socket, Manager, managersts(2739)

All these properties are not mentioned as options in intellisense, or in he socketIO docs... they shouldn't be needed when creating an io()

How can I use Typescript with the SocketIO client?

like image 392
Kokodoko Avatar asked Jul 24 '19 19:07

Kokodoko


People also ask

How do I use socket IO client in typescript?

io-client ( save-dev is ok if your HTML will load the JavaScript payload from the SocketIO server), then in your TypeScript code const socket=io(); will be automatically typed: const socket: SocketIOClient. Socket . NOTE: @types/socket. io-client is a stub types definition.

What is the difference between Socket.IO and socket IO client?

socket-io. client is the code for the client-side implementation of socket.io. That code may be used either by a browser client or by a server process that is initiating a socket.io connection to some other server (thus playing the client-side role in a socket.io connection).


2 Answers

The io function has return type SocketIOClient.Socket and not SocketIOClientStatic. If you use that type, or leave out the signature altogether, it works as expected:

import io from 'socket.io-client';

const socket: SocketIOClient.Socket = io('http://localhost');
const anotherSocket = io('http://localhost');
like image 172
Oblosys Avatar answered Sep 19 '22 21:09

Oblosys


On client version 4.x

import { io, Socket } from "socket.io-client";
like image 38
Viktor Tarnavskyi Avatar answered Sep 19 '22 21:09

Viktor Tarnavskyi