Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
    ]
}
like image 747
Jatt Avatar asked Apr 13 '18 12:04

Jatt


People also ask

How do you know if something is undefined in TypeScript?

We can use typeof or '==' or '===' to check if a variable is null or undefined in typescript.

How do you say not 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.

How do you check if a value is undefined or null in TypeScript?

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 .

How do I fix TypeScript object is possibly 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.


1 Answers

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).

like image 160
Paleo Avatar answered Nov 14 '22 22:11

Paleo