liveBook · Manning

Membership operator

As explained in Essential TypeScript 5, Third Edition

The in keyword is a JavaScript operator that tests whether an object defines a specified property or inherited property.

The JavaScript in operator checks whether an object has a named property, including a property inherited from its prototype. In TypeScript, this test can act as a type guard for union-shaped objects. section 10.2.6

Distinguishing products from people

For a (Product | Person)[] union, test for a property unique to one shape: if ("city" in item), TypeScript narrows item to Person; otherwise, it treats item as Product. The branches can then safely access city or price. section 10.2.6

Build reliable membership checks by following these constraints:

  • Choose a property included in one shape but not the other, such as city for Person or price for Product. section 10.2.6
  • Avoid inaccurate tests that do not definitively distinguish the possible object types. section 10.2.6

How Essential TypeScript 5, Third Edition covers it

How deep it goes
Explains syntax, narrowing behavior, and discriminating-property selection, but defers the full catalogue of common guard errors.
Examples
Uses Product and Person objects, city and price checks, and compiled output distinguishing Bob from three products.
What it assumes
Assumes familiarity with JavaScript objects, properties, TypeScript shapes, and union-typed arrays.
What you can do after
Apply it via JavaScript and TypeScript to select safely narrowed branches for heterogeneous object arrays.
How it connects
Connects membership tests with type guards, union types, object shapes, and property access.

Also explained in

Compare how 8 books explain membership operator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Essential TypeScript 5, Third Edition. The section links point to the parts of the book it draws on.