Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
访问jwt解码对象时出现Typescript错误_Typescript_Jwt - Fatal编程技术网

访问jwt解码对象时出现Typescript错误

访问jwt解码对象时出现Typescript错误,typescript,jwt,Typescript,Jwt,我已经安装了@types/jwt decode,我很难让它正常工作 import jwtDecode from 'jwt-decode' ... let decodedToken = jwtDecode(token); console.log(decodedToken) // this works! I can see the full object console.log(decodedToken.exp) // error Object is of type 'unknown'.ts(25

我已经安装了
@types/jwt decode
,我很难让它正常工作

import jwtDecode from 'jwt-decode'

...
let decodedToken = jwtDecode(token);
console.log(decodedToken) // this works! I can see the full object
console.log(decodedToken.exp) // error Object is of type 'unknown'.ts(2571)

问题是jwtDecode不知道您的令牌中有什么,因为它可能是任何东西。因此,它使用类型
unknown
来表示解码的JWT的结果是未知的

为了解决这个问题,您需要创建一个
接口
,描述您希望在JWT中看到的内容,并告诉
jwtDecode
将其用作解码令牌的返回类型。您可以这样做:

接口MyToken{
名称:字符串;
经验:数量;
//JWT中的其他内容。
}
const decodedToken=jwtDecode(令牌);
console.log(decodedToken.exp);//作品

在v3.1.1上,最近添加了类型定义

import jwt_decode, { JwtPayload } from 'jwt-decode'

const decodedToken = jwt_decode<JwtPayload>(token)
然后呢,

const decodedToken = jwtDecode<customJwtPayload>(token);
const decodedToken=jwtDecode(令牌);

只要我提供包含
exp
声明的令牌,我对您的代码(使用包jsonwebtoken)没有问题。您没有向我们显示令牌或
console.log(decodedToken)
的结果。它是否包含
exp
?感谢您的提示。为了解析非标准声明,我将其与如下扩展类型一起使用:type customJwtPaylod=JwtPayload&{preferred_username:string};let decoded=jwt_decode(令牌);console.log(已解码。首选\u用户名);明亮的谢谢你的主意@Martina
const decodedToken = jwtDecode<customJwtPayload>(token);