0
votes

Getting a compile-time error on (process.env.PORT - 100) in the below conditional statement.

const port = process.env.PORT ? (process.env.PORT - 100) : 3000;

Error says:

The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.

3

3 Answers

3
votes

Interface ProcessEnv is defined as follows:

interface ProcessEnv {
    [key: string]: string | undefined;
}

This means you need to parse this string with parseInt to compile cleanly

0
votes

We need to convert process.env.PORT string to number. The corrected code statement is:

const port = process.env.PORT ? (+process.env.PORT - 100) : 3000;

I'm not using parseInt because parseInt(null) returns NaN but +null returns 0

0
votes
let foo = (condition) ? true : false;
const port = process.env.PORT ? (process.env.PORT - 100) : 3000;

Just to be clear. If your $PORT is "80" you want const port to be -20?

You often see people do this:

const port = process.env.PORT | 3000;

Or:

const port = parseInt(process.env.PORT) | 3000;