1

I have the following code:

if (event.hasOwnProperty('body')) {
  Context.request = JSON.parse(event.body) as T;
} else {
  Context.request = event;
}

where event is defined as:

private static event: aws.IGatewayEvent | ut.IGenericEvent;

The first definition has a "body" attribute, the second does not. Still I'd expect that my conditional statement should let Typescript see that the only case left -- aka, where the object implements the aws.IGatewayEvent interface -- and not give the error:

Property 'body' does not exist on type 'IGenericEvent | IGatewayEvent'.

ken
  • 8,763
  • 11
  • 72
  • 133
  • 2
    very similar question https://stackoverflow.com/questions/43496154/accessing-different-properties-in-a-typescript-union-type – artem May 26 '17 at 19:41
  • That's a useful link @artem but I still the same errors when I abstract the type checking to a function. – ken May 28 '17 at 18:22

1 Answers1

1

Property 'body' does not exist on type 'IGenericEvent | IGatewayEvent'.

Property checks do not form an automatic type guard in TypeScript. You will have to create a user defined type guard for now.

More

basarat
  • 261,912
  • 58
  • 460
  • 511
  • Thanks! You're right setting up a user defined type guard did work. I think what @artem was pointing to me probably was the same solution but at first I missed it because I'd casually thought that the "as" operator was being used instead of the "is" operator which i'd not seen before. In any case, thanks for the help. – ken May 29 '17 at 15:28