0

I am very new to typescrypt, and I'm currently in the process of migrating a project from JS to TS. While I was changing some things on my server endpoints, an error appeared:

Property 'email' does not exist on type 'string | JwtPayload'

This is my code so far:

try {
    const token = await TokenController.getTokenFromRequest(req);
    const decoded = jwt.decode(token);
    const user = await AuthController.getUserByMail(decoded.username); // <- Error appears here
    res.json(user);
} catch (error: any) {
    ErrorController.errorCallback(error, res);
}

Edit: My code for 'getUserByMail' looks like so:

static async getUserByMail(email: string, includePassword = false) {
   let query = User.findOne({
       email: email
   });

   if (!includePassword) {
       query.select('-password');
   }

   return query.exec();
}

I know that the error happens because I'm trying to access a property that string doesn't have. Any suggestions?

Daniel Corona
  • 839
  • 14
  • 34

1 Answers1

0

Create global.d.ts:

// global.d.ts
declare module "jsonwebtoken" {
    export interface JwtPayload {
        //make optional so when you try to decode stuff other than user it will show it can be undefined
        email?: string;
    }
}
Hostek
  • 509
  • 3
  • 9
  • That gives me an ```Property 'decode' does not exist on type 'typeof import("jsonwebtoken")'``` error on my ```jwt.decode()``` function – Daniel Corona Aug 26 '22 at 17:24