[SOLVED] Argument of type 'string | undefined' is not assignable to parameter of type 'string' – TypeScript error


TS error "Object is undefined"

Trying to access "userid" from my headers.
It keeps throwing the error "Argument of type ‘string | undefined’ is not assignable to parameter of type ‘string’.
Type ‘undefined’ is not assignable to type ‘string’."

enter image description here


When I have already defined userid as string or undefined why does this error pop up??
Any idea anyone????

Adding a check before accessing apiGateway event

if (apiGateway.event !== undefined) {
   const { userid } = req.apiGateway.event.headers;
} else {
   throw new badRequestException() 



Judging by your definition of MyRequest:

  • apiGateway can be undefined
  • event cannot be undefined
  • headers cannot be undefined
  • userid can be undefined

So right off the bat, writing req.apiGateway.event.headers will fail, because if apiGateway is undefined, then accessing .event on it will crash. So Typescript does not allow that.

There are three ways around this:

  1. Explicitly check against it. Something like if (req.apiGateway === undefined) { throw new badRequestException(); }
  2. If you’re certain that it can’t be undefined, you can force TypeScript to accept it. Write req.apiGateway!.event. Mind you, if apiGateway does happen to be undefined at runtime, you’ll get an exception. So only use this if you are absolutely 100% sure that it cannot under any circumstance be undefined.
  3. Accept that it can be undefined and coerce everything else to undefined as well. Write req.apiGateway?.event – in this case .event will also be considered as undefined-able. If req.apiGateway happens to be undefined in runtime, then req.apiGateway?.event will also be undefined. And so on and so forth. This means that you’ll also have to add ?. to the rest of the line: req.apiGateway?.event?.headers. And the result of the whole expression is ALSO undefined-able, so you’ll probably need to use more undefined-checks later.

Now, for your second problem. Currently your userid local variable has the type string|undefined. That us because req.apiGateway.event.headers.userid is string|undefined. This means that at runtime it can be either a string, or undefined. However the method updateNotification() expects a simple string as its parameter. It cannot deal with undefined values. If you were to pass it undefined, who knows what would happen (probably an exception). Therefore Typescript does not allow this. And, again, you can use the above methods for dealing with it.

Answered By – Vilx-

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *