Skip to content
AgileLogics
4 min read

Union Types

Prerequisites: Basic types

A union type says a value can be one of several specific types, written with |.

function printId(id: string | number) {
    console.log(`ID: ${id}`);
}

printId(101);
printId("A101");
printId(true); // Argument of type 'boolean' is not assignable...

Unions are how TypeScript models "this can genuinely be one of a few things" precisely, instead of falling back to the anything-goes any.