Issue
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
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).
Answered By - Paleo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.