4

I am using React Typescript with socket.io-client 4.0.0 and @types/socket.io-client 3.0.0. All is good up to a point in the code:

socket = io.connect(`ws://${WS_DOMAIN}:${WS_PORT}`, { transports: ["websocket"] });

I am getting the following error on io.connect:

any
Property 'connect' does not exist on type '{ (opts?: Partial<ManagerOptions &
SocketOptions> | undefined): Socket<DefaultEventsMap, DefaultEventsMap>; (uri: string, 
opts?: Partial<...> | undefined): Socket<...>; (uri: string | Partial<...>, opts?: 
Partial<...> | undefined): Socket<...>; }'.ts(2339)

I would like the error to go away but of course, I do not know how to get rid of it. This is the only error I have in my tsx file.

It is worth to mention this is a class-based component. The IO is imported as such:

import { io } from 'socket.io-client';

and type is assigned before initialization of the class:

let socket: any;

3 Answers 3

8

I would install "@types/socket.io" and then on client side, import like this:

import * as io from "socket.io-client";
const socket = io.connect("http://localhost:4000");

It cleared the error for me.

Sign up to request clarification or add additional context in comments.

1 Comment

This answer is deprecated now as the types are bundled with socket.io.
6

Looking at the documentation I have noticed that the way IO connection is used is as follows:

io(`ws://${WS_DOMAIN}:${WS_PORT}`, { transports: ["websocket"] });

so without the io.connect part

This has also resolved my issue. Hope this helps someone that might encounter similar problem.

Comments

0

[2022]:In the type script react project this might help you. For the latest socket.io-client this is working fine for me.

I have solve this issue by with this following code.

import { io } from 'socket.io-client';
const ChatRoom =({username,room})=>{
 const socket = io('http://localhost:3001');
 const joinRoom = () => {
    if (username !== "" && room !== "") {
      socket.emit("join_room", room);
     
    }

useEffect(()=>{
    joinRoom();
},[room])
  };


  return (
    <div className="App">
      <ChatComponent socket={socket} username={username} room={room} />
    </div>
  );
}

Comments

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.