Narrowing Using In

What

The in operator is a JavaScript feature that checks if a property exists on an object. TypeScript uses this to narrow types within a union.

How

By checking for a property that only exists on one member of a union, you can narrow the type to that specific member:

type TextMsg = { content: string };
type ImageMsg = { url: string };

function display(msg: TextMsg | ImageMsg) {
  if ("content" in msg) {
    // msg is narrowed to TextMsg
    console.log(msg.content);
  }
}

Why

The in operator is a great alternative to discriminated unions when you don’t have control over the type definitions (e.g., when using a third-party library) or when you don’t want to add extra “tag” properties to your objects.

Summary

Use the in operator for quick, structural narrowing when a discriminant property isn’t available.