首页 > 解决方案 > 类型“未定义”不可分配给类型“字符串 | 缓冲区 | {键:字符串| 缓冲; 密码:字符串;} | 获取公共密钥或秘密'

问题描述

JWT 验证码 这是使用 typescript 验证 jwt 的验证功能。

public verify(
    token: string,
    secretOrPublicKey?: string | Buffer,
    options?: jwt.VerifyOptions
  ): Promise<object | string> {
    if (!secretOrPublicKey) {
      secretOrPublicKey = this.secretOrPublicKey;
    }

    return new Promise((resolve, reject) => {
      jwt.verify(
        token,
        secretOrPublicKey,
        options,
        (err: jwt.VerifyErrors, decoded: object | string) => {
          if (err) {
            reject(err);
          } else {
            resolve(decoded);
          }
        }
      );
    });
  }

我发现secrectOrPublicKey下面的警告线以及如何解决这个问题。任何评论都会对我很有帮助。

(parameter) secretOrPublicKey: string | Buffer | undefined Argument of type 'string | Buffer | undefined' is not assignable to parameter of type 'string | Buffer | { key: string | Buffer; passphrase: string; } | GetPublicKeyOrSecret'. Type 'undefined' is not assignable to type 'string | Buffer | { key: string | Buffer; passphrase: string; } | GetPublicKeyOrSecret'.ts(2345)

标签: javascriptnode.jstypescriptexpressjwt

解决方案


遇到此类问题时,只需遵循库使用的类型https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/jsonwebtoken/index.d.ts#L198

secretOrPublicKey: Secret | GetPublicKeyOrSecret,

secretOrPublicKey不应该是可选参数


推荐阅读