使用@types/jsonwebtoken的sign函数时遭遇类型错误的解决咨询
问题
使用@types/jsonwebtoken的sign函数时出现类型错误,代码如下:
const token = await sign( { userId: user.user_id }, config.jwtSecret, { expiresIn: '2d' } )
config.jwtSecret的类型为string,报错信息:
Argument of type 'string' is not assignable to parameter of type 'null'.ts(2345)
错误源于sign函数的重载定义:
export function sign( payload: string | Buffer | object, secretOrPrivateKey: Secret, options?: SignOptions, ): string; export function sign( payload: string | Buffer | object, secretOrPrivateKey: null, options?: SignOptions & { algorithm: "none" }, ): string;
尝试将config.jwtSecret设为any时,又必须添加{ algorithm: "none" }参数,请问如何修复?
修复方案
1. 为config.jwtSecret指定Secret类型
Secret是@types/jsonwebtoken导出的合法密钥类型,包含string、Buffer等合法格式。直接给密钥指定该类型即可解决类型不匹配问题:
import { Secret } from 'jsonwebtoken'; // 定义config时明确类型 const config = { jwtSecret: 'your-actual-secret' as Secret };
或者在调用sign时临时断言类型:
const token = sign( { userId: user.user_id }, config.jwtSecret as Secret, { expiresIn: '2d' } );
2. 确认导入的sign函数正确
检查导入语句,确保没有误导入其他同名函数,正确的导入方式为:
import { sign } from 'jsonwebtoken';
3. 避免使用any类型
用any会绕过TS类型检查,导致编译器匹配到secretOrPrivateKey: null的重载分支,因此必须添加algorithm: "none"参数。坚持使用Secret类型才能匹配正常的签名重载,同时保留类型校验的安全性。
内容的提问来源于stack exchange,提问作者Driscoll Johnson
相关产品推荐
相关产品推荐

