打字稿jsonwebtoken jwt.verify许诺返回对象不能分配给接口

时间:2019-09-10 18:26:03

标签: typescript promise async-await jwt

我对Typescript还是很陌生,我不确定要使用什么正确的语法。

我正在使用诺言从jwt.verify-jsonwebtoken返回解码后的内容。它可以按预期工作,并返回一个包含user.id,iat和有效期的对象,但是在解决承诺中会出现以下类型错误。

“类型'object'的参数不能分配给类型'IVerifiedUserType | PromiseLike | undefined'的参数。”

下面是我要返回的接口和代码。我正在使用异步等待诺言。

export interface IVerifiedUserType {
  id: number;
  iat: number;
  exp: number;
}

const verifyToken = (token: string, config: IConfigType): Promise<IVerifiedUserType> =>
      new Promise((resolve, reject) => {
        if (config.secrets.jwt) {
          jwt.verify(token, config.secrets.jwt, (err, decoded) => {
            if (err) {
              return reject(err);
            }
            if (typeof decoded === "object") {
              resolve(decoded);
            }
          });
        }
      });

const verifiedToken = await authService.verifyToken(token, config);

我使用“ jsonwebtoken”:“ ^ 8.5.1”和“ @ types / jsonwebtoken”:“ ^ 8.3.3”(对于类型)。

1 个答案:

答案 0 :(得分:0)

我相信打字稿不知道您的情况decoded中的解码标记的类型,因此您需要对其进行转换

您可以通过将错误强制转换为 any 来消除错误,但在这种情况下,您将失去类型检查。

resolve(decoded as any)

但更好的解决方案是 resolve(decoded as VerifiedUserType)

你可以省略if (typeof decoded === "object")