TypeScript / TypeScript Advanced Types

Using Type Assertions and Type Guards

In this tutorial, we will delve into Type Assertions and Type Guards in TypeScript. You'll learn how they provide you with control over the types and allow for more robust type-ch…

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Covers advanced type concepts in TypeScript, including mapped types, conditional types, and type manipulation.

1. Introduction

In this tutorial, we'll explore Type Assertions and Type Guards in TypeScript. Type Assertions allow you to tell the compiler "trust me, I know what I'm doing," and Type Guards help you narrow down the type of an object within a certain scope.

By following this tutorial, you'll learn how to use these features to create more robust and safe TypeScript code.

Prerequisites: Familiarity with TypeScript and basic programming concepts like variables, types, and functions.

2. Step-by-Step Guide

Type Assertions

In TypeScript, type assertions are a way to tell the TypeScript compiler that you are sure about the type of a variable. This does not restructure or reformat the data in any way, but it does stop TypeScript from inferring the type.

Syntax:

let someVariable: any = "this is a string";
let strLength: number = (<string>someVariable).length;

Or:

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

Type Guards

Type guards allow you to narrow down the type of an object within a certain scope. This is done by using type-checking functions that return a boolean indicating whether the specific type matches.

Syntax:

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
    }
}

3. Code Examples

Type Assertions

let someVariable: any = "Hello World";
let strLength: number = (<string>someVariable).length;
console.log(strLength); // outputs: 11

Here, we are asserting that someVariable is a string, so we can use the .length property associated with strings.

Type Guards

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

let item: any = 10;

if (isNumber(item)) {
    console.log(item.toFixed(2)); // outputs: "10.00"
}

In this example, the isNumber function is a type guard. When we use it in the if statement, TypeScript knows that item is a number in that if block.

4. Summary

In this tutorial, we've learned about type assertions and type guards in TypeScript. We've seen how type assertions allow us to override TypeScript's inferred types in any way we want, and how type guards can help us narrow down types within a certain scope.

For further study, I recommend exploring the official TypeScript documentation and practicing with more complex examples.

5. Practice Exercises

  1. Write a function that uses a type guard to determine if an array contains only strings.
  2. Use type assertions to convert a string to a number and find its square root.

Solutions

function isStringArray(value: any): value is string[] {
    return Array.isArray(value) && value.every(item => typeof item === 'string');
}

let arr = ['hello', 'world'];
if (isStringArray(arr)) {
    console.log(arr.join(' ')); // Outputs: "hello world"
}
let str: any = "4";
let num: number = <number><unknown>str;
console.log(Math.sqrt(num)); // Outputs: 2

These exercises should help you get a practical understanding of how to use type assertions and type guards in TypeScript. Keep practicing and exploring these concepts to gain a deeper understanding.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Time Zone Converter

Convert time between different time zones.

Use tool

Backlink Checker

Analyze and validate backlinks.

Use tool

Meta Tag Analyzer

Analyze and generate meta tags for SEO.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help