Issue
I have installed @types/jwt-decode
and I’m having trouble getting this to work.
import jwtDecode from 'jwt-decode'
...
let decodedToken = jwtDecode(token);
console.log(decodedToken) // this works! I can see the full object
console.log(decodedToken.exp) // error Object is of type 'unknown'.ts(2571)
Solution
The issue is jwtDecode
is unaware of what is inside your token, as it could be anything. Because of this, it uses the type unknown
to signify that result of the decoded JWT is, unknown.
To get around this you will need to create an interface
describing what you expect to be in your JWT and tell jwtDecode
to use it as the return type of the decoded token. You can do so like this:
interface MyToken {
name: string;
exp: number;
// whatever else is in the JWT.
}
const decodedToken = jwtDecode<MyToken>(token);
console.log(decodedToken.exp); // works!
Answered By – domsim1
Answer Checked By – Robin (BugsFixing Admin)