我在javascript中有以下代码:

if (token) {

    // verifies secret and checks exp
    jwt.verify(token, Config.Secret, function(err, decoded) {
      if (err) {
        return res.json({ success: false, message: 'Failed to authenticate token.' });
      } else {
        // if everything is good, save to request for use in other routes
        req.decoded = decoded;
        next();
      }
    });

  } else {

    // if there is no token
    // return an error
    return res.status(403).send({
        success: false,
        message: 'No token provided.'
    });

  }

想要将其重写为 typescript ,但出现错误Property decoded does not exists on type Request

任何想法如何解决?

最佳答案

如果您不想创建扩展Request的新类,则可以将request作为一个对象进行访问,例如:

req['decoded'] = decoded;

如果仍然无法解决,您可能必须将req转换为对象( typescript ):
(<Object>req)['decoded'] = decoded;

您甚至可以强制转换req以键入any并将访问解码为属性( typescript ):
(<any>req).decoded = decoded;

09-16 17:24