CUSTOMISED
Expert-led training for your team
Dismiss
How to Use Type Guards in TypeScript

4 April 2023

How to Use Type Guards in TypeScript

How to Use Type Guards in TypeScript

 TypeScript provides type guards as a way to narrow down the type of a variable based on a specific condition. In this how-to guide, I will explain how to use type guards in TypeScript and provide some code examples.

 Step 1: Defining a Type Guard

 A type guard is a function that returns a boolean value and is used to narrow down the type of a variable based on a specific condition. Here's an example of a type guard that checks if a variable is a string:

 

function isString(value: unknown): value is string {

  return typeof value === 'string';

}

 The ‘unknown’ type allows any value to be passed in. The function then checks if the value is a string and returns a boolean value. The value is string syntax is used to indicate that the function returns a type predicate.

 Step 2: Using a Type Guard

Once you have defined a type guard, you can use it to narrow down the type of a variable in your code. Here's an example:

function logLength(value: unknown) {

  if (isString(value)) {

    console.log(value.length);

  } else {

    console.log('Value is not a string.');

  }

}

 In this example, the ‘isString type guard is used to check if the value is a string. If it is, the length of the string is logged to the console. If it's not a string, a message is logged instead.

 Step 3: Creating Custom Type Guards

You can also create custom type guards for more complex types. Here's an example of a custom type guard for checking if an object has a ‘name’ property:

 

interface Person {

  name: string;

  age: number;

}

 

function hasNameProperty(value: unknown): value is Person {

  return typeof value === 'object' && value !== null && 'name' in value;

}

 The ‘unknown’ type is used to allow any value to be passed in. The function then checks if the value is an object, not null, and has a ‘name’ property. The ‘value is Person’ syntax is used to indicate that the function returns a type predicate for the ‘Person’ interface.

 Step 4: Using Custom Type Guards

 Once you have defined a custom type guard, you can use it to narrow down the type of a variable in your code. Here's an example:

 

function logPersonName(person: unknown) {

  if (hasNameProperty(person)) {

    console.log(person.name);

  } else {

    console.log('Value is not a person.');

  }

}

 In this example, the ‘hasNamePropertycustom type guard is used to check if the person variable has a ‘name’ property. If it does, the name is logged to the console. If not, a message is logged instead.

Conclusion

In this how-to guide, I have explained how to use type guards in TypeScript, including defining a type guard, using a type guard, creating custom type guards, and using custom type guards. By using type guards, you can write more robust and error-free code in TypeScript. 

Official Documentation:

For more information about using type guards in TypeScript, you can refer to the official TypeScript documentation:

TypeScript: https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types

I hope this guide helps you get started with using type guards in TypeScript.

We would recommend our course in TypeScript.

 

About the author: Daniel West
Tech Blogger & Researcher for JBI Training

CONTACT
+44 (0)20 8446 7555

[email protected]

SHARE

 

Copyright © 2023 JBI Training. All Rights Reserved.
JB International Training Ltd  -  Company Registration Number: 08458005
Registered Address: Wohl Enterprise Hub, 2B Redbourne Avenue, London, N3 2BS

Modern Slavery Statement & Corporate Policies | Terms & Conditions | Contact Us

POPULAR

Rust training course                                                                          React training course

Threat modelling training course   Python for data analysts training course

Power BI training course                                   Machine Learning training course

Spring Boot Microservices training course              Terraform training course

Kubernetes training course                                                            C++ training course

Power Automate training course                               Clean Code training course