TypeScript · Narrowing and unions

in operator

Narrows by checking whether a property exists on the value.

Syntax
if ("id" in value)

Example

Example
type A = { id: string };
type B = { name: string };
function label(value: A | B) {
  return "id" in value ? value.id : value.name;
}

More in this group

Assertion function Discriminated union Exhaustive switch instanceof guard Non-null assertion Type assertion Type predicate typeof guard

Learn this in the course

Reference pages are the quick answer. The course explains the why, shows the full example and ends with a challenge.

Open the course