How to deal with nested objects which might be string or undefined in a clean way? So I'm parsing an object using Typescript. I am pushing a value from within the object into an array of strings.
Here's the code:
if (data.InstanceStatuses != undefined)
            if (data.InstanceStatuses[0].InstanceId != undefined)
                instanceIds.push(data.InstanceStatuses[0].InstanceId as string)

I feel there must be a better way to deal with the fact that both data.InstanceStatuses and data.instanceStatuses[0].InstanceId can be of type string || undefined, however I am not sure how to get it down to a simpler statement with less IF blocks.
Any ideas?
Typescript has supported optional chaining for a while. To do this concisely and avoid the somewhat inelegant as string type assertion, extract the possibly nested value into a variable, then check its typeof against string:
const instanceId = data.InstanceStatuses?.[0].InstanceId;
if (typeof instanceId === 'string') {
  instanceIds.push(instanceId);
}

This way, instanceId will be either the nested value, or, if InstanceStatuses doesn't exist, it'll be undefined. So, it'll only push to the array if the nested value exists and the value is a string.