JWT验证码这是使用typescript验证JWT的验证函数。
public verify(
token: string,
secretOrPublicKey?: string | Buffer,
options?: jwt.VerifyOptions
): Promise<object | string> {
if (!secretOrPublicKey) {
secretOrPublicKey = this.secretOrPublicKey;
}
return new Promise((resolve, reject) => {
jwt.verify(
token,
secretOrPublicKey,
options,
(err: jwt.VerifyErrors, decoded: object | string) => {
if (err) {
reject(err);
} else {
resolve(decoded);
}
}
);
});
}
我在下面的secrectOrPublicKey
上找到了警告行,以及如何解决这个问题。任何评论对我都很有帮助。
(parameter) secretOrPublicKey: string | Buffer | undefined Argument of type 'string | Buffer | undefined' is not assignable to parameter of type 'string | Buffer | { key: string | Buffer; passphrase: string; } | GetPublicKeyOrSecret'. Type 'undefined' is not assignable to type 'string | Buffer | { key: string | Buffer; passphrase: string; } | GetPublicKeyOrSecret'.ts(2345)
遇到这种问题时,只需遵循库使用的类型https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/jsonwebtoken/index.d.ts#L198
secretOrPublicKey: Secret | GetPublicKeyOrSecret,
secretOrPublicKey
不应该是可选参数
您已经通过以下操作确保secretOrPublicKey
的值不能是undefined
:
if (!secretOrPublicKey) {
secretOrPublicKey = this.secretOrPublicKey;
}
但是typescript将secretOrPublicKey
的类型指定为string | Buffer | undefined
,因为它在函数参数中是可选的。您的支票不会更新该类型分配。Typescript仍然认为它可能是undefined
,并抛出一个错误。
最简单的解决方法是在函数签名中指定默认值,这样就不可能将secretOrPublicKey
的值设置为undefined
:
public verify(
token: string,
secretOrPublicKey: string | Buffer = this.secretOrPublicKey,
options?: jwt.VerifyOptions
): Promise<object | string> {