1
votes

Im quite new to Typescript, I'm not sure what the correct syntax is to use.

I'm using a promise to return the decoded content from jwt.verify - jsonwebtoken. It works as expected and returns an object containing the user.id, the iat, and the expiry but the following type error appears on the resolve promise.

"Argument of type 'object' is not assignable to parameter of type 'IVerifiedUserType | PromiseLike | undefined'."

Below is the Interface and code that I am returning. Im using async await on the promise.

export interface IVerifiedUserType {
  id: number;
  iat: number;
  exp: number;
}

const verifyToken = (token: string, config: IConfigType): Promise<IVerifiedUserType> =>
      new Promise((resolve, reject) => {
        if (config.secrets.jwt) {
          jwt.verify(token, config.secrets.jwt, (err, decoded) => {
            if (err) {
              return reject(err);
            }
            if (typeof decoded === "object") {
              resolve(decoded);
            }
          });
        }
      });

const verifiedToken = await authService.verifyToken(token, config);

Im using "jsonwebtoken": "^8.5.1", and "@types/jsonwebtoken": "^8.3.3", for types.

1

1 Answers

0
votes

I believe that typescript doesn't know the type of decoded token in your case decoded, so you need to cast it.

You can get rid of the error by cast it to any, but in that case, you would lose type checking.

resolve(decoded as any)

But better solution would be resolve(decoded as VerifiedUserType)

and you can omit if (typeof decoded === "object")