TypeScript type guards are essential for ensuring type safety and robustness in your code. This blog explores the concept of type guards, their importance, and how to effectively use them in TypeScript.
TypeScript, being a statically typed superset of JavaScript, provides powerful features to catch errors at compile time rather than runtime. Type guards play a crucial role in ensuring type safety and preventing unexpected runtime errors.
Type guards are functions that return a boolean value to assert the type of a variable. They help TypeScript compiler narrow down the type of a variable within a certain block of code.
function isNumber(value: any): value is number {
return typeof value === 'number';
}
let num: any = 5;
if (isNumber(num)) {
console.log('The variable is a number.');
} else {
console.log('The variable is not a number.');
}
TypeScript allows defining union types to represent values that can be of multiple types. Type guards can be used effectively with union types to narrow down the possible types within a conditional block.
type Shape = Circle | Square;
interface Circle {
radius: number;
}
interface Square {
sideLength: number;
}
function isCircle(shape: Shape): shape is Circle {
return (shape as Circle).radius !== undefined;
}
let shape: Shape = { radius: 5 };
if (isCircle(shape)) {
console.log('The shape is a circle.');
} else {
console.log('The shape is not a circle.');
}
In addition to built-in type guards like typeof and instanceof, TypeScript allows defining custom type guards based on specific conditions or structures.
function isEmail(input: string): input is Email {
return /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/.test(input);
}
let userInput: string = 'example@email.com';
if (isEmail(userInput)) {
console.log('The input is a valid email.');
} else {
console.log('The input is not a valid email.');
}
TypeScript type guards are powerful tools for ensuring type safety and writing more robust code. By understanding and effectively using type guards, developers can catch type-related errors early in the development process, leading to more reliable and maintainable code.