JWT:'string类型的参数undefined'不能分配给类型为'Secret'的参数
我正在使用 dotenv 来声明 JWT_SECRET 环境变量,它显示了标题中提到的错误。
.env
NODE_ENV="development"
JWT_SECRET="mySecretString"
环境.d.ts
import { Secret } from 'jwt-promisify'
declare global {
namespace NodeJS {
interface ProcessEnv {
JWT_SECRET: Secret,
NODE_ENV: 'development' | 'production',
PORT?: number | string
}
}
}
export {}
我在我的路由文件中使用即时签名令牌 JWT_SECRET
路由文件
NODE_ENV="development"
JWT_SECRET="mySecretString"
这里的智能感知正在工作,但是当我运行应用程序或编译它时出现错误。
错误
error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'Secret'.
Type 'undefined' is not assignable to type 'Secret'.
32 const token = await jwt.sign({ id: newUser.id }, process.env.JWT_SECRET)
~~~~~~~~~~~~~~~~~~~~~~
回答
jwt.sign(data, process.env.SIGNATURE_KEY as string, {
expiresIn: '30d',
algorithm: "HS256"
}, (err, encoded)=>{
err ? reject(err) : resolve(encoded)
})
对于打字稿,我认为类型转换有效。我也没有实现 async-await 因为 sign 方法没有被暗示为Promise. 但我想它也有效!
THE END
二维码