I tried using @types/socket.io-redis
like so:
import { Server as HttpServer } from 'http';
import socketIo, { Socket } from 'socket.io';
import redis, { RedisAdapter } from 'socket.io-redis';
export default function setupWebsocket(server: HttpServer) {
const io = socketIo().listen(server);
io.adapter(redis(process.env.REDIS_URL));
const adapter: RedisAdapter = io.of('/').adapter; // Error here
}
At the section where the Error here comment is, I got a red underline at the adapter
variable with the error:
Type 'Adapter' is not assignable to type 'RedisAdapter'.
Property 'uid' is missing in type 'Adapter'.
Can anyone help me fix this issue? I'm quite new to Typescript
This is correct behaviour, type of io.of('/').adapter
is Adapter
. Fact that you assigned specific implementation(RedisAdapter
) of interface(Adapter
) don't change property type, as later you might change to different implementation of Adapter
.
Possible solution might be to assign adapter directly after creation
import { Server as HttpServer } from 'http';
import socketIo, { Socket } from 'socket.io';
import redis, { RedisAdapter } from 'socket.io-redis';
export default function setupWebsocket(server: HttpServer) {
const io = socketIo().listen(server);
const adapter: RedisAdapter = redis(process.env.REDIS_URL);
io.adapter(adapter);
//... more code here
}
Other solution is to cast to desired type
const adapter: RedisAdapter = io.of('/').adapter as RedisAdapter;