I have a bunch of places in my code where I rely on an environment variable and want to throw an error if it does not exist:
if(!process.env.SOME_VAR) {
throw new Error('Missing required environment variable "SOME_VAR"');
}
doSomethingWithVar(process.env.SOME_VAR);
// function doSomethingWithVar(var: string);
I was wondering if there was a way to utilize TypeScript's asserts-keyword to write a function to do the assertion for me? Something like
function assertEnvironmentVariable<T extends string>(name: T):
asserts NodeJS.ProcessEnv[name] is string {
if(!process.env[name]) {
throw new Error(`Missing required environment variable "${name}"`);
}
}
// Usage:
assertEnvironmentVariable('SOME_VAR');
// no type error here since `assertEnvironmentVariable` already made sure it exists
doSomethingWithVar(process.env.SOME_VAR);
However, this definition of assertEnvironmentVariable does not work - is this possible at all?
Edit: Playground link