TypeScript · Lesson 33 of 120
The in Operator
Which shape?.
When a union contains different object shapes, check for a property with the in operator. If the property is there, TypeScript knows which shape you have.

- Different shapes
- Check a property
- in
Bike or e-bike
A bike has a model. An e bike also has a range. If range is in the object, it's an e bike. Run it. Each item is described correctly.
app.tstypescript
type Bike = { model: string };
type EBike = { model: string; rangeKm: number };
function describe(item: Bike | EBike): string {
if ("rangeKm" in item) {
return `${item.model} (electric, ${item.rangeKm} km)`;
}
return item.model;
}
console.log(describe({ model: "City 200" }));
console.log(describe({ model: "Volt 7", rangeKm: 90 }));Output
City 200 Volt 7 (electric, 90 km)
Summary
The in operator narrows object unions by checking for a property. Next, literal types.
Key takeaways- 'rangeKm' in item
- Object unions
- Narrowed
Next up: Literal Types — exact values