Skip to content

Edvins Antonovs

Exploring TypeScript: type guards

TypeScript type guards are a way to narrow down the variable type within a conditional block. They are handy when working with union types or when TypeScript's type inference system needs some additional information to determine the exact type of a variable. Type guards allow you to perform runtime checks that help TypeScript understand the types more accurately.


There are several ways to create type guards in TypeScript:

  1. typeof type guards: You can use the typeof operator to check the type of a variable, like checking if a variable is a string, number, boolean, etc.
1function isString(value: any): value is string {
2 return typeof value === 'string';
3}
4
5const example: string | number = 'Hello';
6if (isString(example)) {
7 // TypeScript now knows 'example' is a string here.
8 console.log(example.length);
9}
  1. instanceof type guards: The instanceof the operator checks if an object is an instance of a particular class or constructor function.
1class Animal {
2 name: string;
3 constructor(name: string) {
4 this.name = name;
5 }
6}
7
8class Dog extends Animal {
9 bark() {
10 console.log('Woof!');
11 }
12}
13
14function isDog(animal: Animal): animal is Dog {
15 return animal instanceof Dog;
16}
17
18const myAnimal: Animal = new Dog('Rover');
19if (isDog(myAnimal)) {
20 // TypeScript now knows 'myAnimal' is a Dog.
21 myAnimal.bark();
22}
  1. Custom type guards: You can create your custom type guards by defining a function with a specific return type that indicates whether the provided value matches a certain type or condition.
1function isEvenNumber(value: number): value is number {
2 return value % 2 === 0;
3}
4
5const num: number | string = 42;
6if (isEvenNumber(num)) {
7 // TypeScript now knows 'num' is a number.
8 console.log(num + 2);
9}
  1. Type predicates: TypeScript allows you to use type predicates in function signatures to specify a condition that narrows the type of the argument. This is similar to custom type guards but is specified as part of a function's signature.
1function isString(input: any): input is string {
2 return typeof input === 'string';
3}
4
5function processInput(input: any): void {
6 if (isString(input)) {
7 // TypeScript knows 'input' is a string in this block.
8 console.log(input.length);
9 }
10}

These type guards help TypeScript understand the types more accurately and provide better type checking and autocompletion support in your code. They are beneficial when working with complex data structures and union types, ensuring your code is type-safe and maintainable.

© 2024 by Edvins Antonovs. All rights reserved.