Today is my second day diving into the world of typescript and I find myself puzzled by a particular situation:
Let's imagine we have a file named .env
which contains a variable called ACCESS_TOKEN_SECRET
ACCESS_TOKEN_SECRET = 9i0d98f7a0sd87fy03eihdq2iudh...
We may need to pass this variable to a function in our TypeScript code, like so:
const accessToken = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET)
At this stage, our IDE might flag up an issue stating that the process.env.ACCESS_TOKEN_SECRET variable may not be a string
Argument of type 'string | undefined' is not assignable to parameter of type 'Secret'.
Type 'undefined' is not assignable to type 'Secret'.ts(2345)
To address this, I decided to check if the process variable is indeed a string
if(typeof process.env.ACCESS_TOKEN_SECRET !== 'string') throw new Error()
const accessToken = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET)
However, I still feel somewhat uncertain about this solution. Is this really the correct way TypeScript expects me to tackle this issue?