You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript集成Redis v4.0.4时调用get方法出现类型错误的解决方案咨询

解决Redis v4 + TypeScript回调风格的类型错误

这个问题的核心是Redis v4 默认采用 Promise 风格 API,你开启了legacyMode想用回调写法,但类型定义没有自动适配这种模式。下面给你两种可行的解决方案:

方案一:改用 Promise/Async-Await(官方推荐)

Redis v4 主推异步非阻塞的 Promise 风格,不仅类型匹配更顺畅,代码可读性和维护性也更好:

修改你的isCached中间件:

import { Response, Request, NextFunction } from "express";
import * as redis from "redis";

const redisClient = redis.createClient({ 
  url: "redis://127.0.0.1:6379", // 注意要加上redis://协议前缀,否则v4会解析失败
  legacyMode: true, 
});

// 初始化Redis连接(v4必须调用此方法)
(async () => {
  await redisClient.connect();
})();

const isCached = async (req: Request, res: Response, next: NextFunction) => {
  const { idUser } = req.params;
  try {
    const data = await redisClient.get(idUser);
    if (data != null) {
      console.log("we Found it in Redis ");
      res.send(data);
    } else {
      console.log("User Not Found  ");
      next();
    }
  } catch (err) {
    res.status(500).send(err);
  }
};

export default isCached;

方案二:继续使用回调风格(适配类型)

如果你一定要保留回调写法,需要手动指定客户端类型为LegacyClient,让 TypeScript 识别回调格式的 API:

import { Response, Request, NextFunction } from "express";
import * as redis from "redis";
import { LegacyClient } from "redis";

// 明确指定客户端类型为LegacyClient
const redisClient = redis.createClient({ 
  url: "redis://127.0.0.1:6379",
  legacyMode: true, 
}) as LegacyClient;

redisClient.connect();

const isCached = (req: Request, res: Response, next: NextFunction) => {
  const { idUser } = req.params;
  // 现在TypeScript会正确识别回调风格的get方法
  redisClient.get(idUser, (err, data) => {
    if (err) {
      res.status(500).send(err);
    }
    if (data != null) {
      console.log("we Found it in Redis ");
      res.send(data);
    } else {
      console.log("User Not Found  ");
      next();
    }
  });
};

export default isCached;

错误原因补充

Redis v4 对 API 做了重构,默认所有命令都返回 Promise,回调风格被归类到 legacy 兼容模式中;而@types/redis v4 的类型定义默认适配 Promise 风格,直接用回调就会触发类型不匹配的报错。

内容的提问来源于stack exchange,提问作者enesbugrac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 16:22:27