How to type NodeJS environment variables using TypeScript
Type 'undefined' is not assignable to type 'string'
If you've been using TypeScript for a while you might have encountered the following error when accessing an environment variable.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.ts(2322)
This can be resolved by Typing process.env in the NodeJS Namespace. We do this by creating the file additional.d.ts in the root directory and definining the environment variable types.
declare namespace NodeJS {
interface ProcessEnv {
ACCESS_KEY_ID: string;
SECRET_ACCESS_KEY: string;
EMAIL: string;
}
}
Make sure to add additional.d.ts to the includes array of tsconfig.json
{
...
"include": ["additional.d.ts"]
}
The error is now gone