我正在尝试编译一个 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/