Type guards inferred from in operator

The in operator now acts as a narrowing expression for types.

For a n in x expression, where n is a string literal or string literal type and x is a union type, the “true” branch narrows to types which have an optional or required property n, and the “false” branch narrows to types which have an optional or missing property n.

Example

  1. interface A { a: number };
  2. interface B { b: string };
  3. function foo(x: A | B) {
  4. if ("a" in x) {
  5. return x.a;
  6. }
  7. return x.b;
  8. }