Node-jsonwebtoken: typescript verify unable to get data from decoded

Created on 7 Jun 2018  路  5Comments  路  Source: auth0/node-jsonwebtoken

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"

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 verify should be something like verify<DecodedParams>(...): DecodedParams

All 5 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

shea256 picture shea256  路  3Comments

cope picture cope  路  4Comments

usamamashkoor picture usamamashkoor  路  4Comments

ngminhduong picture ngminhduong  路  3Comments

AndreOneti picture AndreOneti  路  3Comments