grooot
grooot

Reputation: 466

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

undefined

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

Update:
Adding a check before accessing apiGateway event

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

return......

Upvotes: 2

Views: 13686

Answers (2)

woda
woda

Reputation: 105

always when you got this error it's good to just check if variable has some value:

if(!variable) return
// continue

after this if type of variable will be string instead of string | undefined

Upvotes: 3

Vilx-
Vilx-

Reputation: 107002

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.

Upvotes: 6

Related Questions