Reputation: 6856
this is my code
const data = jwt.verify(token, process.env.JWT_Confirm_KEY);
when i use data.id i get error
await db.ref(`/users/${data.id}`).once("value")
Property 'id' does not exist on type 'object'.ts(2339)
one way to get rid of the error
interface IdEmail {
id: string;
email: string;
}
const data = jwt.verify(token, process.env.JWT_Confirm_KEY) as IdEmail;
what other ways are there to get rid of this error ?
Upvotes: 1
Views: 1933
Reputation: 1774
This could be another minimal approach with Typescript. Note that you also could use the decoded data already within the jwt.verify
callback. I just prefer to do it this way for program control flow.
let isJWTValid = false;
jwt.verify(token, "mysecret", (error, data) => {
if (error) {
return;
}
isJWTValid = true;
});
if (!isJWTValid) {
return "invalid token";
}
const decodedToken = jwt.decode(token) as { myValue: string }; // <--- Cast here for Typescript
const { myValue } = decodedToken;
console.log("myValue", myValue);
Upvotes: 0
Reputation: 16127
You can create a custom generic function, it will look the same as your comment, but I think this way will be better.
const verify = <T extends object>(token: string, secret: string): T => {
return jwt.verify(token, secret) as T;
};
const sign = <T extends object>(payload: T, secret: string): string => {
return jwt.sign(payload, secret);
};
export default const MyJwt = {
sign,
verify,
}
Usage,
import MyJwt from './MyJwt';
const data = MyJwt.verify<IdEmail>(token, process.env.JWT_Confirm_KEY);
// data now is a IdEmail
Upvotes: 1
Reputation: 11
After you verify, you must decode token. Try this:
const { id, email } = jwt.decode(token, { json: true }) as IdEmail;
Upvotes: 1