typescript - jsonwebtoken typescript 编译问题?

标签 typescript json-web-token

我正在尝试编译一个 typescript 文件,它一直从编译器中抛出这个错误: 错误 TS2339:类型“string”上不存在属性“payload”|目的'。 “string”类型上不存在属性“payload”。

有问题的代码:

decode(token: string): any {
  const decodedJWT = jwt.decode(token, { complete: true });

  const issuer = decodedJWT.payload.iss;
                           ^^^^^^^^^
  return {};
}

我正在使用 @types/jsonwebtoken 库来定义类型。任何帮助将不胜感激。

最佳答案

这个错误是TypeScript类型检查导致的,jwt.decode()的返回类型是null |对象 | string,如果你确定 jwt.decode() 总是返回一个对象,你可以将 decodedJWT 转换为 any 类型避免此错误:

decode(token: string): any {
  const decodedJWT = jwt.decode(token, { complete: true });

  const issuer = (decodedJWT as any).payload.iss;
  return {};
}

在上面的例子中,它可能会在运行时导致异常,因为jwt.decode() 可能会返回null 或一个字符串,但只会返回一个object。包含属性payload,所以你最好以更安全的方式处理返回值:

decode(token: string): any {
  const decodedJWT = jwt.decode(token, { complete: true });

  if (decodedJWT === null) {
       // deal with null
  } else if (typeof decodedJWT === 'string') {
       // deal with string
  } else {
       const issuer = (decodedJWT as any).payload.iss; // cast to `any` type
  }

  return {};
}

关于typescript - jsonwebtoken typescript 编译问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47045185/

相关文章:

typescript 继承扩展属性

typescript - 是否可以在服务器发送的事件之间添加延迟?

具有通用返回类型的 Typescript 函数

security - JOSE jwe/jws 有效负载

angularjs - NodeJs中间件设置头

html - 卸载然后重新安装软件包后,我开始收到 "export was not found in ' @angular/core' "

javascript - 'string | null' 类型的参数不可分配给 'ValueFn<SVGPathElement, Datum[], string | number | boolean | null>' 类型的参数

c# - 解码 JSON Web token (Xamarin.Android)

session - 有环回 + Passport + jwt 的例子吗?