Mastering TypeScript Type Guards
Learn about TypeScript type guards and how to use them to narrow types.
Introduction to Type Guards
In TypeScript, a type guard is a way to narrow the type of a value within a specific scope.
Step 1: Define a Type Guard
Create a new file called type-guards.ts and add the following code:
function isString<T>(value: T): value is string {
return typeof value === 'string';
}
This function is a type guard that checks if a value is a string.
Step 2: Use the Type Guard
Add the following code to the type-guards.ts file:
const value: string | number = 'hello';
if (isString(value)) {
console.log(value.toUpperCase());
}
This code uses the isString type guard to narrow the type of the value variable.
Step 3: Create a More Complex Type Guard
Add the following code to the type-guards.ts file:
interface Bird {
fly(): void;
}
interface Fish {
swim(): void;
}
function isBird<T>(value: T): value is Bird {
return (value as Bird).fly !== undefined;
}
This code defines a type guard that checks if a value is a Bird.
Ready for more? These paid resources pick up where this lesson leaves off.
Project-based TypeScript video courses — the perfect paid next step after these free lessons.
Browse on Udemy →Hand-picked TypeScript books to master the fundamentals offline.
See on Amazon →Some links on this page are affiliate links: we may earn a commission at no extra cost to you. We only recommend tools we believe are genuinely useful.