TypeScriptLesson 12 of 16
Type guards: typeof, in, instanceof
A type guard is a check after which TypeScript knows the exact type of a value. You need them most for unknown and for data from the outside world.
Key points
- typeof suits primitives: "string", "number", "boolean".
- "meow" in pet checks for a property and picks the right union member.
- instanceof works with classes: error instanceof ApiError.
- The predicate value is Contact turns a plain checking function into a type guard.
- filter with a predicate returns an array of the right type, not unknown[].
Example
class ApiError { constructor(public code: number) {}} interface Cat { meow(): string;}interface Dog { bark(): string;} function speak(pet: Cat | Dog): string { return "meow" in pet ? pet.meow() : pet.bark(); // "in" narrows to Cat} function isText(value: unknown): value is string { return typeof value === "string"; // a custom type predicate} function explain(error: unknown): string { if (error instanceof ApiError) return `API error ${error.code}`; if (isText(error)) return `Message: ${error}`; return "Unknown error";} console.log(speak({ meow: () => "Meow!" }));console.log(explain(new ApiError(404)));console.log(explain("timeout"));console.log(explain(42));explain accepts anything, yet each branch knows the type: ApiError has code, and the string can go into text. Without the isText predicate TypeScript would not narrow unknown to string.
Task
How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.Turn isContact into a value is Contact predicate with a full check, print every contact as "Ivan: 555-0101" and finish with "Valid: 2 of 5".
Output
What your program prints appears here.