Kokodoko
Kokodoko

Reputation: 28128

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?

Upvotes: 8

Views: 11147

Answers (3)

Viktor Tarnavskyi
Viktor Tarnavskyi

Reputation: 621

On client version 4.x

import { io, Socket } from "socket.io-client";

Upvotes: 7

Niklas
Niklas

Reputation: 457

I'd like to extend the answer of Oblosys:

If the esModuleInterop flag is active and you get an error message like

This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag.

then do the import with the as-Syntax:

import * as io from 'socket.io-client';

const socket: SocketIOClient.Socket = io('http://localhost');

Upvotes: 0

Oblosys
Oblosys

Reputation: 15096

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');

Upvotes: 17

Related Questions