Issue
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’."
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......
Solution
Judging by your definition of MyRequest
:
apiGateway
can be undefinedevent
cannot be undefinedheaders
cannot be undefineduserid
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:
- Explicitly check against it. Something like
if (req.apiGateway === undefined) { throw new badRequestException(); }
- If you’re certain that it can’t be
undefined
, you can force TypeScript to accept it. Writereq.apiGateway!.event
. Mind you, ifapiGateway
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. - 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. Ifreq.apiGateway
happens to be undefined in runtime, thenreq.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)