I've been pondering on how to ensure TypeScript acknowledges that I am verifying the existence of my variables before using them. Below is the code snippet :
Here's the function responsible for these checks:
function verifyEnvVars(){
if (!process.env.DRIVER_PATH) {
throw new Error('Environment variable DRIVER_PATH has not been set');
}
}
Now, let me show you how it's implemented:
export async function performTask() {
verifyEnvVars();
const driverPath = path.resolve(process.env.DRIVER_PATH); <- This line triggers a TS error
// ...additional code here
}
This is the TypeScript error I encounter:
Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.ts(2345)
Interestingly, if I conduct the check directly rather than within a function, TypeScript doesn't complain. However, I prefer maintaining clean and organized code.