2

I am trying to decode the JWT token in order to check wheather is it valid or not. But I am getting the error that the decoded object is possibly 'undefined'

import jwt_decode, { JwtPayload } from "jwt-decode";
    if (token) {
      const decoded = jwt_decode<JwtPayload>(token || "") || null;

      if (decoded) {
        const currentTime = Date.now() / 1000;
        if (decoded?.exp < currentTime) {  //Object is possibly 'undefined'.
          dispatch(logout());
          localStorage.removeItem("token");
          setLoading(false);
        }
      }
}
Illyrian
  • 429
  • 4
  • 16

1 Answers1

4

decoded.exp is possibly undefined, so you have to check it first before comparing it to currentTime

if (decoded?.exp && decoded.exp < currentTime) { }
axtck
  • 3,707
  • 2
  • 10
  • 26
  • the `?` in `decoded?.exp < currentTime` already does that. It can end up comparing `undefined < currentTime` instead but that's not a problem either because that's always `false` – zapl Sep 21 '22 at 16:11
  • @zapl exp is possibly undefined too, it does seem to fix the compilation error try it out here https://www.typescriptlang.org/play?ssl=7&ssc=2&pln=1&pc=1#code/MYewdgzgLgBAJgU1IuAuGBXMiBmBLMBOGAHxgG8YEAPAB3TAwFsAjBAJ1M2wX0OIC+MALwUqddFlwEiMAQG4AUIrw4YACkTIiASgqKYMUJFjAM7dgjBQAKniYIRMACIBDKAgB0YEAHd1egD0MACMAAwRSoaqGlogKJ40tDAAZCnwSPFEAPyJdDAAPEbmltZ2DnqUMAZyigJAA – axtck Sep 21 '22 at 16:18
  • 2
    oops, right, `strictNullChecks` doesn't like undefined < number – zapl Sep 21 '22 at 16:22