TExcelTAD
Home › TypeScript › TS Basic Generics

TypeScript Basic Generics

Imagine a function that returns the first element of an array. You could type the parameter as any[], but then the result is any and all type safety is lost. You could write firstNumber, firstString, firstUser… but that is repetitive. Generics solve this: they let you write code that works with many types while still remembering which type it was used with.

Generic functions

A type parameter is declared in angle brackets, conventionally named T. It acts like a variable that holds a type:

ts · try it yourself
function first<T>(items: T[]): T | undefined {
  return items[0];
}

const n = first([10, 20, 30]);        // n: number | undefined
const s = first(["red", "green"]);    // s: string | undefined

console.log(n, s);
console.log(s?.toUpperCase());
10 red
RED

You almost never need to write first<number>(…) yourself — TypeScript infers T from the argument. Because the result keeps the precise type, using it wrongly is caught:

ts · try it yourself
function first<T>(items: T[]): T | undefined {
  return items[0];
}

const total: number = first(["a", "b"]) ?? 0;
main.ts(5,7): error TS2322: Type 'string | 0' is not assignable to type 'number'.
  Type 'string' is not assignable to type 'number'.

Several type parameters

A function may have more than one type parameter:

ts · try it yourself
function pair<A, B>(a: A, b: B): [A, B] {
  return [a, b];
}

function mapValues<T, U>(items: T[], fn: (item: T) => U): U[] {
  const out: U[] = [];
  for (const item of items) out.push(fn(item));
  return out;
}

console.log(pair("age", 31));
console.log(mapValues(["a", "bb", "ccc"], (w) => w.length));
[ 'age', 31 ]
[ 1, 2, 3 ]

In mapValues, T is inferred as string from the array, so the callback parameter w is a string, and U is inferred as number from what the callback returns.

Constraints with extends

Sometimes the code needs something from the type — for example, a length property. T extends Something restricts T to types that have at least that shape:

ts · try it yourself
function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}

console.log(longest("apple", "fig"));
console.log(longest([1, 2], [1, 2, 3]));
console.log(longest(10, 20));
main.ts(7,21): error TS2345: Argument of type 'number' is not assignable to parameter of type '{ length: number; }'.

Numbers have no length, so the last call is rejected. Remove that line and the program prints apple and [ 1, 2, 3 ].

Generic types and interfaces

Type aliases, interfaces and classes can take type parameters too. The built-in Array<T>, Promise<T> and Map<K, V> are all generic types.

ts · try it yourself
interface ApiResponse<T> {
  ok: boolean;
  data: T;
}

class Stack<T> {
  private items: T[] = [];
  push(item: T): void {
    this.items.push(item);
  }
  pop(): T | undefined {
    return this.items.pop();
  }
  get size(): number {
    return this.items.length;
  }
}

const res: ApiResponse<string[]> = { ok: true, data: ["x", "y"] };
console.log(res.data.join(","));

const stack = new Stack<number>();
stack.push(1);
stack.push(2);
console.log(stack.pop(), stack.size);
x,y
2 1

Default type parameters

Type parameters can have defaults, just like function parameters: interface Box<T = string> { value: T }. Then Box alone means Box<string>.

Syntax Meaning
<T> a type parameter
<T extends X> T must be assignable to X
<T = X> T defaults to X when not given or inferred
fn<number>(…) pass the type argument explicitly

Tip: If a type parameter appears only once in a signature, you probably don't need it. Generics are useful when they connect types — an input to an output, or one parameter to another.

Test yourself

Given function id<T>(x: T): T, what is the type of id("hi")?

  1. any
  2. unknown
  3. string
  4. T

What does <T extends { length: number }> mean?

  1. T inherits from a class
  2. T must have a numeric length property
  3. T is an array
  4. T has a default of { length: number }

Which of these is a built-in generic type?

  1. Promise<T>
  2. string
  3. never
  4. object