Based on the definition provided for MyRequest
:
apiGateway
may be undefined
event
cannot be undefined
headers
cannot be undefined
userid
can be undefined
Given this, attempting to access req.apiGateway.event.headers
directly will result in an error since if apiGateway
is undefined, accessing .event
on it will cause a crash. Therefore, TypeScript does not permit this action.
There are three approaches to address this issue:
- Explicitly check for its existence. For example,
if (req.apiGateway === undefined) { throw new badRequestException(); }
- If you are confident that it will never be
undefined
, you can force TypeScript to accept it by using req.apiGateway!.event
. Keep in mind that if apiGateway
happens to be undefined during runtime, it will lead to an exception. Thus, only utilize this method if you are absolutely certain it will always have a value.
- Accept the possibility of it being undefined and set everything else to undefined as well. Utilize
req.apiGateway?.event
- in this scenario, .event
will also be considered potentially undefined. If req.apiGateway
turns out to be undefined at runtime, then req.apiGateway?.event
will also be undefined. This pattern continues onwards. Consequently, you will need to append ?.
throughout the line: req.apiGateway?.event?.headers
. Furthermore, the outcome of the entire expression is also nullable, prompting the necessity for more checks for undefined later on.
Moving on to your second dilemma. Presently, your local variable userid
is of type string|undefined
. This is due to
req.apiGateway.event.headers.userid
being of type
string|undefined
. Hence, during runtime, it could either be a string or undefined. However, the function
updateNotification()
requires a plain
string
as input. It cannot handle undefined values. Passing undefined might lead to unexpected outcomes (likely an exception). As a result, TypeScript prohibits this behavior. Once again, you can employ the previously mentioned methods to handle this situation.