Here is how I use the method:
const decoded = jwt.verify(req.body.jwtToken, process.env.JWTSECRET);
return res.send({
user: decoded.user // <-- error here
});
and I have a linter error : "Property user does not exists on type "obejct|string"
const decoded: any = jwt.verify(req.body.jwtToken, process.env.JWTSECRET);
return res.send({
user: decoded.user // <-- error here
});
Tout need to cast decoded as any :
(decoded as any).user
I don't think that casting the decoded as any is a good solution. In any case the best thing will be to create an interface and cast it to that.
In the other hand I think that this library has a poor typing implementation. The verify function should be typed. So verify should be something like verify<DecodedParams>(...): DecodedParams
This is the first thing that pops up when you Google "jsonwebtoken verify typescript," so I think it deserves a clearer conclusion.
Casting like @ghost suggested works, e.g.
const decoded = <any>verify(token, secret);
But I think @luisgurmendezMLabs has a point: It would be much more intuitive if the previous code could be rewritten:
const decoded = verify<IDecoded>(token, secret);
It looks like @zRelux never had time to complete his pull request, so as of now, the first way is currently the only way.
Someone please jump in if I got any of the above wrong. Also, if there's some interest, I could maybe look into implementing the second way.
Is there any reason this was closed? It still seems relevant.
Most helpful comment
I don't think that casting the decoded as any is a good solution. In any case the best thing will be to create an interface and cast it to that.
In the other hand I think that this library has a poor typing implementation. The verify function should be typed. So
verifyshould be something likeverify<DecodedParams>(...): DecodedParams