Wai Phyo Naing
Wai Phyo Naing

Reputation: 13

Type 'undefined' is not assignable to type 'string | Buffer | { key: string | Buffer; passphrase: string; } | GetPublicKeyOrSecret'

JWT Verification Code This is verification function to verify jwt using typescript.

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);
          }
        }
      );
    });
  }

And I found waring line on secrectOrPublicKey that is following and how to solve this please. Any comment would very helpful to me.

(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)

Upvotes: 0

Views: 644

Answers (2)

Linda Paiste
Linda Paiste

Reputation: 42188

You've made sure that the value of secretOrPublicKey can't be undefined by doing this:

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

But typescript assigned the type of secretOrPublicKey as string | Buffer | undefined because it was optional in the function arguments. That type assignment doesn't get updated by your check. Typescript still thinks it could be undefined and throws an error.

The easiest fix is to assign the default value in the function signature so that there is never a possibility that the value of secretOrPublicKey is set to undefined:

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

Upvotes: 0

diedu
diedu

Reputation: 20785

When having this kind of issue just follow the types that the library uses https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/jsonwebtoken/index.d.ts#L198

secretOrPublicKey: Secret | GetPublicKeyOrSecret,

secretOrPublicKey shouldn't be an optional parameter

Upvotes: 1

Related Questions