TypeScript · Lesson 37 of 120
Type Guards
Is.
Sometimes the check is too complex for typeof or in. You can write your own check, as a function. Its return type, value is type, tells TypeScript what a true result means.

- Complex checks
- Your own function
- value is Type
A custom guard
Is E bike checks for a range that's a number. Its return type says, if this returns true, the item is an E bike. Filter uses the guard, so the result is typed as E bikes. Run it.
app.tstypescript
type Bike = { model: string };
type EBike = { model: string; rangeKm: number };
function isEBike(item: Bike | EBike): item is EBike {
return "rangeKm" in item && typeof item.rangeKm === "number";
}
const range: (Bike | EBike)[] = [{ model: "City 200" }, { model: "Volt 7", rangeKm: 90 }];
const electric = range.filter(isEBike);
console.log(electric.map(b => `${b.model}: ${b.rangeKm} km`));Output
[ 'Volt 7: 90 km' ]
Use them carefully
TypeScript trusts your guard completely. If the check is wrong, the types are wrong too. Keep guards small, and test them.
| key | value |
|---|---|
| Return type | item is EBike |
| TypeScript | trusts it |
| Wrong check | wrong types |
| Keep them | small and tested |
Summary
Type guards are functions whose return type, value is type, teaches TypeScript a new check. Next, practice with payment results.
Key takeaways- item is EBike
- filter(isEBike)
- Trusted
Next up: Practice: Payment Results — unions together