TypeScript
Beginner
1 min read
typeof, instanceof, and in Guards
Example
// typeof guard — primitives
function processInput(input: string | number | boolean): string {
if (typeof input === "string") return input.toUpperCase();
if (typeof input === "number") return input.toFixed(2);
return input ? "YES" : "NO";
}
// instanceof guard — classes
class ValidationError extends Error {
constructor(public field: string, message: string) {
super(message);
this.name = "ValidationError";
}
}
class NetworkError extends Error {
constructor(public statusCode: number, message: string) {
super(message);
this.name = "NetworkError";
}
}
function handleError(err: Error): void {
if (err instanceof ValidationError) {
console.error(`Validation failed on field: ${err.field}`);
} else if (err instanceof NetworkError) {
console.error(`HTTP ${err.statusCode}: ${err.message}`);
} else {
console.error("Unknown error:", err.message);
}
}
// 'in' guard — object shapes
interface Square { kind: "square"; side: number }
interface Triangle { kind: "triangle"; base: number; height: number }
type Polygon = Square | Triangle;
function describePolygon(p: Polygon): string {
if ("side" in p) return `Square with side ${p.side}`;
return `Triangle with base ${p.base}`;
}
// Truthiness narrowing
function greet(name: string | null | undefined): string {
if (name) return `Hello, ${name}!`; // name is string here
return "Hello, stranger!";
}
Related Resources
TypeScript Reference
Complete tag & property list
TypeScript How-To Guides
Step-by-step practical guides
TypeScript Exercises
Practice what you've learned
More in TypeScript