Using Assertions for Error Prevention

Tutorial 3 of 5

Using Assertions for Error Prevention in TypeScript

1. Introduction

Goal of the Tutorial

This tutorial aims to introduce assertions and type guards in TypeScript. These are powerful features that help in ensuring type safety and preventing common errors.

Learning Outcomes

By the end of this tutorial, you will be able to use assertions and type guards effectively to enhance the quality of your TypeScript code by preventing potential errors.

Prerequisites

Basic knowledge of TypeScript is required to follow along with this tutorial.

2. Step-by-Step Guide

Assertions

In TypeScript, an assertion is a way to tell the compiler "trust me, I know what I'm doing." It doesn't change the runtime behavior of the program but helps in type checking during development.

Example

let someVar: any = "hello";
let strLength: number = (<string>someVar).length;

In the above example, <string>someVar is a type assertion. We are telling the compiler that someVar is a string.

Type Guards

Type guards are expressions that perform a runtime check and narrow down the type of a variable within a certain scope.

Example

function isNumber(x: any): x is number {
  return typeof x === "number";
}

In the above example, x is number is a type guard. If the function returns true, TypeScript compiler will know that x is a number within that if-block.

3. Code Examples

Example 1: Using Assertion

let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;

In this example, we're asserting that someValue is a string. So, we can access the .length property which is specific to string type.

Example 2: Using Type Guards

function isString(test: any): test is string {
  return typeof test === "string";
}

function example(foo: any) {
  if (isString(foo)) {
    console.log("It's a string!");
    console.log(foo.length); // string function
  }
}

example("hello world");

In this example, isString(foo) is a type guard. If it returns true, then within the if-block, TypeScript knows that foo is a string.

4. Summary

In this tutorial, we learned about assertions and type guards in TypeScript. We learned how to use assertions to tell the compiler to treat a variable as a specific type. We also learned how to use type guards to check the type of a variable at runtime.

5. Practice Exercises

Exercise 1

Use type guard to write a function that takes an array of strings and numbers and returns a new array with only strings.

Exercise 2

Use assertion to write a function that takes an object with an any type and a string as a key, and returns the length of the value of that key.

Solutions

Solution to Exercise 1

function filterStringsFromMixedArray(arr: (string | number)[]): string[] {
  return arr.filter((item): item is string => typeof item === 'string');
}

In this solution, we're using a type guard item is string to filter out the strings from the array.

Solution to Exercise 2

function getLengthOfValue(obj: any, key: string): number {
  return (obj[key] as string).length;
}

In this solution, we're using an assertion to tell the compiler that obj[key] is a string, so we can use the length property.

These exercises should help solidify your understanding of assertions and type guards. Try to use these concepts in your own TypeScript code to enhance type safety.