TypeScript实现与ioredis set同参数类型的多客户端写入函数
解决方案
直接利用TypeScript的Parameters工具类型和Rest参数语法就能解决这两个问题,代码实现如下:
import Redis from 'ioredis'; class RedisClientManager { private clients: Redis[]; constructor(clients: Redis[]) { this.clients = clients; } // 复用ioredis set方法的参数类型,支持直接传参 public writeAll(...args: Parameters<typeof Redis.prototype.set>) { return this.clients.map(client => client.set(...args)); } }
关键细节说明
- 类型检查问题解决:
Parameters<typeof Redis.prototype.set>会自动提取ioredis原生set方法的所有参数类型,调用writeAll时会严格遵循原生set的参数规则,比如键、值、过期参数等的类型和顺序都会被校验,彻底替代any类型。 - 直接传参问题解决:用
...argsRest参数语法,调用时可以像使用普通set方法一样传参,比如:const manager = new RedisClientManager([new Redis(), new Redis()]); // 直接传参,无需包装成数组 manager.writeAll('user:1', '{"name":"foo"}', 'EX', 3600);
如果需要等待所有客户端的写入操作完成,可以改成异步版本:
public async writeAll(...args: Parameters<typeof Redis.prototype.set>) { // 等待所有set操作完成,返回所有结果的数组 return Promise.all(this.clients.map(client => client.set(...args))); }
内容的提问来源于stack exchange,提问作者Shri
相关产品推荐
相关产品推荐

