Mastering TypeScript Type Guards
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.