Video

Watch the full video on YouTube:

Type Assertions

Introduction

In this seventh chapter of our TypeScript series, you’ll learn about Type Assertions, a powerful tool for type narrowing and type management in TypeScript. We’ll cover how to use the as keyword, the danger of double assertions, and how to create exact types with assertion as const.

What is a Type Assertion?

A Type Assertion is a way to tell TypeScript about the specific type of a value when you know more about it than the compiler does. It’s similar to casting in other languages.

Basic Syntax

const someValue: unknown = "Hello, TypeScript!";
const strLength: number = (someValue as string).length;

The as keyword is the primary way to perform type assertions in TypeScript.

Practical Examples

Using querySelector

const element = document.querySelector('#myElement') as HTMLInputElement;
element.value = "Hello";

Using getElementById

const element = document.getElementById('myElement') as HTMLInputElement;
element.value = "Hello";

Type Assertion Rules

TypeScript has specific rules for type assertions:

  1. You can only assert to classes that implement the same interface or that are subtypes of a particular class
  2. You cannot assert to unrelated types without double assertion
  3. The assertion must be compatible with the original type

Double Assertion

Double assertion allows you to convert between incompatible types, but it should be used with caution:

const someValue: string = "Hello";
const num: number = someValue as unknown as number; // Double assertion

Assertion as const

You can use as const to create exact types with literal values:

const config = {
  apiUrl: "https://api.example.com",
  timeout: 5000
} as const; // Exact type with literal values

Type Narrowing vs Type Assertion

Type Narrowing is when you use conditional checks to narrow down the type:

function processValue(value: string | number) {
  if (typeof value === "string") {
    // TypeScript knows value is string here
    return value.toUpperCase();
  }
  return value.toFixed(2);
}

Type Assertion is when you explicitly tell TypeScript the type:

const value: unknown = "Hello";
const str = value as string; // Explicit assertion

Best Practices

  1. Prefer Type Narrowing over Type Assertions when possible
  2. Use Type Assertions when you’re certain about the type
  3. Avoid double assertions unless absolutely necessary
  4. Use as const for immutable data structures
  5. Always validate data from external sources before asserting types

Conclusion

Type Assertions give you more control over TypeScript’s type system, but they should be used judiciously. Type Narrowing is generally safer and more maintainable.

Repository

💻 Repository: https://github.com/radagva/ts-example

Next Steps

🔔 Subscribe to the channel to not miss the next chapters of the TypeScript course!

NestJS API Development Guide 07: POST, Body and DTO Validation