AI Hints
Home›TypeScript Tutorial›Type Guards and Practice
TypeScript · Lesson 37 of 120

Type Guards

Is.

⏱ 2 min read▶ Video at 29:09🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

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.

Type Guards
From the video: Type Guards
  • 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.

keyvalue
Return typeitem is EBike
TypeScripttrusts it
Wrong checkwrong types
Keep themsmall 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