【问题标题】:Argument of type 'string | JwtPayload' is not assignable to parameter of type 'string''string | 类型的参数JwtPayload' 不可分配给“字符串”类型的参数
【发布时间】:2021-09-07 21:57:52
【问题描述】:

我将 Typescript 与 Express 一起使用,并使用 JWT 进行承载授权。现在的情况是,如前所述,我正在使用 JWT 编写授权中间件,并尝试从 JWT 令牌中提取当前用户。

代码在这里:

import * as jwt from 'jsonwebtoken';
import * as dotenv from 'dotenv';
import {NextFunction, Response, Request} from "express";
import {
    VerifyOptions,
    Algorithm,
    JsonWebTokenError,
    TokenExpiredError,
    NotBeforeError,
    Secret,
    JwtPayload
} from "jsonwebtoken";


 ....       

try {
            

    // Verify the token
    let result = jwt.verify(authToken, accessTokenSecret, accessTokenOptions)

    console.log("Type of: String"+(result instanceof String) )

    console.log("Type of: JwtPayload " + (result instanceof JwtPayload) ); // Error



    next();
} catch (error){
   ...
}

}

我正在尝试检查结果是否是 JwtPayload 的实例。但是,JwtPayload 是一个接口。所以,我不断收到这个错误 Argument of type 'string | JwtPayload' 不可分配给“字符串”类型的参数。

假设令牌一直被验证。

结果有以下数据!

{
    user: {id: 1, username: 'ariel'},
    iat: 1234,
    exp: 1278
}

我只是想从结果中解析用户。但是,我不断收到标题中提到的错误。

【问题讨论】:

    标签: javascript typescript express jwt


    【解决方案1】:

    不确定您的问题到底出在哪里(在 sn-p 中看不到),但请尝试使用类型谓词。 即

    function isJWTPayload(value: JWTPayload | String): value is JWTPayload {
      return (value as isJWTPayload).id !== undefined;
    }
    

    查看这里了解更多 https://www.typescriptlang.org/docs/handbook/advanced-types.html#using-type-predicates

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-02
      • 2021-06-16
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      • 2018-04-05
      • 2021-11-23
      • 1970-01-01
      相关资源
      最近更新 更多