Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment variable is not assigning with Typescript

Tags:

typescript

My code is:

const port: Number = process.env.PORT || 3000;

[ts]
Type 'string | 3000' is not assignable to type 'Number'.
  Type 'string' is not assignable to type 'Number'.

I tried

const port: Number = parseInt(process.env.PORT, 10) || 3000;

But it gives me another error:

Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
  Type 'undefined' is not assignable to type 'string'.
(property) NodeJS.Process.env: NodeJS.ProcessEnv

What am I doing wrong?

like image 589
Shamoon Avatar asked May 16 '18 17:05

Shamoon


1 Answers

const port: Number = parseInt(<string>process.env.PORT, 10) || 3000

This solved it. I think it's called Type Assertion

like image 143
Shamoon Avatar answered Sep 20 '22 05:09

Shamoon