DevPath · Learn to code ESPTEN

Introduction to TypeScript

Generics and unions

Union types

A union type indicates that a value can be of one among several types, using |.

let id: number | string;
id = 42;     // valid
id = "abc";  // also valid
// id = true; // ❌ Error

function format(value: number | string): string {
  return `Value: ${value}`;
}

To work with unions safely you use type checks:

function describe(x: number | string): string {
  if (typeof x === "number") return `number ${x.toFixed(2)}`;
  return `text of ${x.length} characters`;
}

Generics (introduction)

Generics let you write code that works with any type without losing the type information. They are written with <T>.

function first<T>(arr: T[]): T {
  return arr[0];
}

const n = first([1, 2, 3]);       // T = number, n is number
const s = first(["a", "b"]);      // T = string, s is string

This way, first preserves the type of the elements of the array it receives, instead of returning any.

Examples

The generic logic works the same in JS

function first(arr) {
  return arr[0];
}
function describe(x) {
  if (typeof x === "number") return "number " + x.toFixed(2);
  return "text of " + x.length + " characters";
}
console.log(first([10, 20, 30]));
console.log(describe(3.14159));
console.log(describe("hi"));
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Interfaces and function typesView the module →