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"
]
}
We can use typeof or '==' or '===' to check if a variable is null or undefined in typescript.
By adding the exclamation mark ( ! ) at the end, you let the TypeScript compiler that there is no way this variable will be undefined or null.
You can use the qualities of the abstract equality operator to do this: if (variable == null){ // your code here. } Because null == undefined is true, the above code will catch both null and undefined .
The "Object is possibly 'undefined'" error occurs when we try to access a property on an object that may have a value of undefined . To solve the error, use the optional chaining operator or a type guard to make sure the reference is not undefined before accessing properties.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With