【问题标题】:Type 'undefined' is not assignable to type 'string | Buffer | { key: string | Buffer; passphrase: string; } | GetPublicKeyOrSecret'类型“未定义”不可分配给类型“字符串 |缓冲区 | {键:字符串|缓冲;密码:字符串; } |获取公共密钥或秘密'
【发布时间】:2021-02-01 19:50:55
【问题描述】:

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)

【问题讨论】:

    标签: javascript node.js typescript express jwt


    【解决方案1】:

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

    secretOrPublicKey: Secret | GetPublicKeyOrSecret,
    

    secretOrPublicKey 不应该是可选参数

    【讨论】:

      【解决方案2】:

      您已通过这样做确保secretOrPublicKey 的值不能是undefined

          if (!secretOrPublicKey) {
            secretOrPublicKey = this.secretOrPublicKey;
          }
      

      但是 typescript 将 secretOrPublicKey 的类型分配为 string | Buffer | undefined,因为它在函数参数中是可选的。您的检查不会更新该类型分配。 Typescript 仍然认为它可能是 undefined 并抛出错误。

      最简单的解决方法是在函数签名中分配默认值,这样secretOrPublicKey 的值就不可能被设置为undefined

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-06
        • 2021-08-19
        • 1970-01-01
        • 2019-10-30
        • 2017-12-29
        • 2021-04-06
        • 2022-01-07
        相关资源
        最近更新 更多