You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

使用jsonwebtoken库时jwt.sign的TypeScript类型错误解决方法咨询

使用jsonwebtoken库时jwt.sign的TypeScript类型错误解决方法咨询

我正在开发一个TypeScript项目,用jsonwebtoken库生成和验证JWT令牌,但调用jwt.sign时碰到了类型错误,折腾了半天也没搞懂问题出在哪,想请大家帮忙看看。

我的代码如下:

import jwt, { Secret, JwtPayload } from "jsonwebtoken";

const JWT_SECRET: Secret = process.env.JWT_SECRET || "kala__30191";
const EXPIRE: string = process.env.JWT_EXPIRE || "30d";

export function generateToken(payload: Record<string, any>): string {
  return jwt.sign(payload, JWT_SECRET, { expiresIn: EXPIRE });
}

export function verifyToken(token: string): Promise<JwtPayload | string> {
  return new Promise((resolve, reject) => {
    jwt.verify(token, JWT_SECRET, (err, decoded) => {
      if (err) {
        return reject(err);
      }
      resolve(decoded as JwtPayload);
    });
  });
}

遇到的错误信息:

No overload matches this call.
Overload 1 of 5, '(payload: string | object | Buffer<ArrayBufferLike>, secretOrPrivateKey: null, options?: (SignOptions & { algorithm: "none"; }) | undefined): string', gave the following error.
Argument of type 'Secret' is not assignable to parameter of type 'null'.
Type 'string' is not assignable to type 'null'.
Overload 2 of 5, '(payload: string | object | Buffer<ArrayBufferLike>, secretOrPrivateKey: Secret | Buffer<ArrayBufferLike> | PrivateKeyInput | JsonWebKeyInput, options?: SignOptions | undefined): string', gave the following error.
Type 'string' is not assignable to type 'number | StringValue | undefined'.
Overload 3 of 5, '(payload: string | object | Buffer<ArrayBufferLike>, secretOrPrivateKey: Secret | Buffer<ArrayBufferLike> | PrivateKeyInput | JsonWebKeyInput, callback: SignCallback): void', gave the following error.
Object literal may only specify known properties, and 'expiresIn' does not exist in type 'SignCallback'. (ts 2769)

我已经安装了jsonwebtoken库和对应的类型定义,但还是报这个错,求指导怎么修复。


解决方案:

这个错误核心是类型不匹配导致的,尤其是expiresIn参数的类型定义和Secret类型的推断问题,以下是几个可行的修复步骤:

  1. 确保依赖版本兼容
    有时候jsonwebtoken@types/jsonwebtoken版本不兼容会引发类型错误,建议安装最新稳定版并保持版本一致:

    npm install jsonwebtoken@latest @types/jsonwebtoken@latest --save
    
  2. 修正expiresIn的类型定义
    错误信息里提到Type 'string' is not assignable to type 'number | StringValue | undefined',这是因为你把EXPIRE定义成了固定string,但jwt.signSignOptionsexpiresIn的合法类型是string | number | undefined。我们可以直接复用库中的类型来保证完全匹配:

    import jwt, { Secret, JwtPayload, SignOptions } from "jsonwebtoken";
    
    const JWT_SECRET: Secret = process.env.JWT_SECRET || "kala__30191";
    // 直接使用SignOptions中的expiresIn类型
    const EXPIRE: SignOptions['expiresIn'] = process.env.JWT_EXPIRE || "30d";
    
  3. 优化verifyToken的类型处理(可选)
    虽然这不是当前错误的原因,但可以让类型逻辑更严谨,避免不必要的断言:

    export function verifyToken(token: string): Promise<JwtPayload | string> {
      return new Promise((resolve, reject) => {
        jwt.verify(token, JWT_SECRET, (err, decoded) => {
          if (err) {
            return reject(err);
          }
          resolve(decoded as JwtPayload | string);
        });
      });
    }
    
  4. 临时方案:类型断言(不推荐过度使用)
    如果上述方法都没解决,可以临时用类型断言告诉TypeScript类型是匹配的,但这只是绕过类型检查,建议优先用前面的方法:

    return jwt.sign(payload, JWT_SECRET as string, { expiresIn: EXPIRE as string });
    

内容来源于stack exchange

火山引擎 最新活动