'How to tell typescript, that process is not undefined?
In the following line of code:
internalWhiteList = process.env.INTERNAL_IP_WHITELIST.split( ',' )
I get an error saying, Object is possibly undefined
. env
variables are loaded into process.env
using the module named dotenv from .env
file placed at the root.
How could I tell typescript, that process
is not undefined?
Here is my tsconfig.json
:
{
"compilerOptions": {
"target": "esnext",
"outDir": "../dist",
"allowJs": true,
"module": "commonjs",
"noEmitOnError": false,
"noImplicitAny": false,
"strictNullChecks": true,
"sourceMap": true,
"pretty": false,
"removeComments": true,
"listFiles": false,
"listEmittedFiles": false
},
"exclude": [
"node_modules",
"test/",
"**/*.spec.ts"
]
}
Solution 1:[1]
Maybe with a non-null assertion operator (!
):
internalWhiteList = process.env.INTERNAL_IP_WHITELIST!.split( ',' )
Or with a if
statement:
if (process.env.INTERNAL_IP_WHITELIST)
internalWhiteList = process.env.INTERNAL_IP_WHITELIST.split( ',' )
What does it mean???
If you look at the type-defs for Node you see:
export interface ProcessEnv {
[key: string]: string | undefined;
}
It's that string | undefined
that means INTERNAL_IP_WHITELIST
is possibly undefined, in which case undefined.split()
is an error, so you need to assert or guard against it being undefined (as this answer demonstrates).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Aaron Beall |