gpt4 book ai didi

typescript - socket.io-redis typescript 错误

转载 作者:可可西里 更新时间:2023-11-01 11:12:38 26 4
gpt4 key购买 nike

我试过像这样使用 @types/socket.io-redis:

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
}

Error here 注释所在的部分,我在 adapter 变量处得到了一条红色下划线,其中有错误:

Type 'Adapter' is not assignable to type 'RedisAdapter'.

Property 'uid' is missing in type 'Adapter'.

谁能帮我解决这个问题?我对 Typescript 很陌生

最佳答案

这是正确的行为,类型为 io.of('/').adapterAdapter .事实上,您分配了接口(interface)(RedisAdapter)的特定实现(Adapter)不会更改属性类型,因为稍后您可能会更改为不同的实现Adapter .

可能的解决方案可能是在创建后直接分配适配器

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
}

其他解决方案是转换为所需的类型

const adapter: RedisAdapter = io.of('/').adapter as RedisAdapter;

关于typescript - socket.io-redis typescript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51476126/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com