首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用Redis类型时的类型错误

使用Redis类型时的类型错误
EN

Stack Overflow用户
提问于 2022-03-19 06:06:51
回答 1查看 2.4K关注 0票数 2

嗨,我试着在打字稿上使用redis,但是这段代码总是给我这个错误。我安装了"redis":"^4.0.4",“@type/redis”:"^4.0.11“。我该如何解决这个问题?

代码语言:javascript
运行
AI代码解释
复制
const idUser: string
Argument of type '[string, (err: any, data: any) => void]' is not assignable to parameter of type '[key: RedisCommandArgument] | [options: CommandOptions<ClientCommandOptions>, key: RedisCommandArgument]'.
  Type '[string, (err: any, data: any) => void]' is not assignable to type '[options: CommandOptions<ClientCommandOptions>, key: RedisCommandArgument]'.
    Type at position 0 in source is not compatible with type at position 0 in target.
      Type 'string' is not assignable to type 'CommandOptions<ClientCommandOptions>'.
        Type 'string' is not assignable to type '{ readonly [symbol]: true; }'.

redis.ts

代码语言:javascript
运行
AI代码解释
复制
import { Response, Request, NextFunction } from "express"; 
    import * as redis from "redis";
    import { RedisClientOptions } from "redis";
    const redisClient = redis.createClient({
      url: "127.0.0.1:6379",
      legacyMode: true,
    });
    const isCached = (req: Request, res: Response, next: NextFunction) => {
      const { idUser } = req.params;
      // getting our data by key (id)
      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  ");
          // go To ⏭️ function or middleware
          next();
        }
      });
    };
    export default isCached;
EN

回答 1

Stack Overflow用户

发布于 2022-03-19 06:32:01

您正在向方法redisClient.get传递2个参数,该方法只接受以下类型的一个参数:

'key: RedisCommandArgument options: CommandOptions,key: RedisCommandArgument‘

基于Node文档,get方法似乎返回了一个承诺,因此我认为您的代码应该如下所示:

代码语言:javascript
运行
AI代码解释
复制
const data = await redisClient
  .get(idUser)
  .catch((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  ");
  // go To ⏭️ function or middleware
  next();
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71538821

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档