This tutorial aims to provide a comprehensive understanding of Type Guards in TypeScript. By the end of this tutorial, you will be able to use Type Guards effectively in your TypeScript projects.
Type Guards are a feature in TypeScript that allows you to check the type of a variable at runtime. This is particularly useful in cases where the type of a variable could be one of several possible types.
One of the simplest ways to create a Type Guard is by using the typeof
operator. This operator can be used to check the type of a variable.
let variable: any = 'I am a string';
if (typeof variable === 'string') {
// In this block, TypeScript knows that `variable` is a string.
console.log(variable.length); // Outputs: 13
}
In the above example, inside the if block, TypeScript knows that variable
is a string. Thus it allows using string methods on variable
.
Another method of creating a Type Guard is to use the instanceof
operator. This operator checks if an object is an instance of a specific class.
class Dog {
bark() {
console.log('Woof!');
}
}
class Cat {
meow() {
console.log('Meow!');
}
}
let pet: Dog | Cat;
if (pet instanceof Dog) {
pet.bark(); // Outputs: "Woof!"
} else {
pet.meow(); // Outputs: "Meow!"
}
In the above example, TypeScript is able to determine the type of pet
using the instanceof
operator.
typeof
function process(input: string | number) {
if (typeof input === "string") {
return input.toUpperCase(); // input is treated as a string here
} else {
return input.toFixed(2); // input is treated as a number here
}
}
console.log(process("Hello")); // Outputs: "HELLO"
console.log(process(100)); // Outputs: "100.00"
In this example, the function process
takes an input which can be a string
or number
. Inside the function, a type guard is used with typeof
to check the type of the input.
instanceof
class Rectangle {
constructor(public width: number, public height: number) {}
area() {
return this.width * this.height;
}
}
class Circle {
constructor(public radius: number) {}
area() {
return Math.PI * this.radius * this.radius;
}
}
function getArea(shape: Rectangle | Circle) {
if (shape instanceof Rectangle) {
return shape.area(); // shape is treated as Rectangle here
} else {
return shape.area(); // shape is treated as Circle here
}
}
console.log(getArea(new Rectangle(5, 10))); // Outputs: 50
console.log(getArea(new Circle(7))); // Outputs: 153.93804002589985
In this example, the function getArea
takes a shape which can be an instance of Rectangle
or Circle
. Inside the function, a type guard is used with instanceof
to check the type of the shape.
In this tutorial, you have learned about Type Guards in TypeScript and how to use them. You've seen how to use the typeof
and instanceof
operators to create Type Guards.
Next steps for learning would be to try using Type Guards in your own TypeScript projects and see how they can help you write safer, more robust code.
Write a function that takes a parameter that can either be a string
or an array of strings
. If it's a string, convert it to uppercase. If it's an array, return the length of the array.
Write a class for Square
and Triangle
each having a method perimeter
. Create a function that takes an object which can be an instance of Square
or Triangle
and returns its perimeter.
Exercise 1:
function process(input: string | string[]) {
if (typeof input === "string") {
return input.toUpperCase();
} else {
return input.length;
}
}
console.log(process("Hello")); // Outputs: "HELLO"
console.log(process(["Hello", "World"])); // Outputs: 2
Exercise 2:
class Square {
constructor(public side: number) {}
perimeter() {
return this.side * 4;
}
}
class Triangle {
constructor(public side: number) {}
perimeter() {
return this.side * 3;
}
}
function getPerimeter(shape: Square | Triangle) {
return shape.perimeter();
}
console.log(getPerimeter(new Square(5))); // Outputs: 20
console.log(getPerimeter(new Triangle(3))); // Outputs: 9
Keep practicing with other types and classes to get more comfortable with Type Guards!