JWT deoded in Typescript gives the error "Object is possibly 'undefined"

Viewed 37

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

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

if (decoded?.exp && decoded.exp < currentTime) { }
Related