21

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?

1
  • 1
    It's complaining about the argument you're passing to parseInt, which may be undefined but must be a string. I think you want parseInt(process.env.PORT || '3000', 10). Commented May 16, 2018 at 17:06

3 Answers 3

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

I think that's not correct? process.env.PORT could be string, or it could be undefined. You're asserting that it can't be undefined here which is false. As the comment-answer above says, you should parseInt(process.env.PORT || '3000') to cover the case when process.env.PORT is undefined.
You can also do: const port: Number = parseInt(`${process.env.PORT}`, 10) || 3000 which will ensure a string is passed to parseInt.
3

I usually do this.

const PORT = Number(process.env.PORT ?? 3000);

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
2

This should work as well.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.