Mastering TypeScript Type Guards
This article was AI-drafted and has not been reviewed yet. Spotted a mistake? Tell us.
Learn about TypeScript type guards and how to use them to narrow the type of a value within a specific scope.
Introduction to Type Guards
In TypeScript, a type guard is a way to narrow the type of a value within a specific scope. It is a function that returns a type predicate, which is a boolean value that indicates whether a value is of a certain type.
Step 1: Define a Type Guard
Create a new file called typeGuards.ts and add the following code:
function isString<T>(value: T): value is string {
return typeof value === 'string';
}
This code defines a type guard function called isString that takes a value of type T and returns a type predicate that indicates whether the value is a string.
Step 2: Use the Type Guard
Create a new file called main.ts and add the following code:
const value: string | number = 'hello';
if (isString(value)) {
console.log(value.toUpperCase());
} else {
console.log(value.toFixed(2));
}
This code uses the isString type guard to narrow the type of the value variable within the if statement. If the value is a string, it logs the uppercase version of the string to the console. If the value is a number, it logs the number with two decimal places to the console.
Ready for more? Optional paid resources that pick up where this lesson leaves off.
Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.
Project-based TypeScript courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for TypeScript books — check the publication year so the examples match current versions.
Search Amazon →