How can I indicate a called function is checking that an object property is null so ts(18047) will not occur?

44 views Asked by At

I have a helper function used in a few different places:

const eventCommonChecks(event: APIGatewayEvent): any {
  if(!event.body) {
    return {
      status: 400,
      body: 'Missing body'
    }
  }

  ... a few other checks
}

When that first function is called in a second function, the second function will return when event.body is null. In the second function, we are guaranteed that event.body will not be null. HOWEVER, if I don't use event.body?.someFieldInBody, the typescript compiler yells at me: "event.body' is possibly 'null'.ts(18047)".

is there a way to decorate my common function to indicate that it's checking that event.body is not null?

const someLambda(event: APIGatewayEvent): any {
  const commonEventCheckResponse = eventCommonChecks(event);
  if (commonEventCheckResponse) {
    return commonEventCheckResponse;
  }


  //'event.body' is possibly 'null'.ts(18047)
  if (!event.body.someFieldInBody) {
    return {
      status: 400,
      body: 'Missing someFieldInBody'
    }
  }

}
1

There are 1 answers

1
Red Forest On BEST ANSWER

There are two ways you can do this:

  1. Add a Non-null assertion operator (ts docs)

    if (!event.body!.someFieldInBody) {

  2. Change the event type in someLambda function to a type where the body field is not null

UPD: one more way to do it

const someLambda(event: APIGatewayEvent): any {
    if (!event.body) {
        return;
    }
    ...
}

so TS will see that now event.body cannot equal null (and other falsy values).