Illyrian
Illyrian

Reputation: 549

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

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

Upvotes: 2

Views: 1525

Answers (1)

axtck
axtck

Reputation: 3965

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

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

Upvotes: 4

Related Questions