0

In typescript, I try to get an attribute from the http request header.

The attribute is a string (of course, it is from the header), I need to parse it into Integer

export const getUser =  async (req, _res, next) => {
  
  const userId: number = parseInt(req.headers.userid);
  
  ... other code 
}

However, the vs code IDE is displaying red line under req.headers.userid and complaining:

(property) IncomingMessage.headers: IncomingHttpHeaders
Argument of type 'string | string[] | undefined' is not assignable to parameter of type 'string'.
  Type 'undefined' is not assignable to type 'string'.ts(2345)

How can I do this simple task?

1
  • Show some more code or even playground link Commented Aug 6, 2021 at 17:01

2 Answers 2

1

That error message says your variable is typed string | string[] | undefined, but parseInt requires string. So you have to handle the other types that userid could be.

Maybe something like:

const userIdHeader = req.headers.userid
if (typeof userIdHeader === 'string') {
  const userId = parseInt(userIdHeader);
}

Now you can only reach that code in the case where you have a string, and typescript knows it.

So the docs on narrowing for more info.

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

Comments

0

I just had the exact same problem and I solved by:

const userIdHeader = req.headers.userid;
const userId = parseInt(String(userIdHeader));

Or better:

const userId = parseInt(String(req.headers.userid));

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.