Tutorials / TypeScript: Beginner to Advanced / Generics: writing reusable typed code

Generics: writing reusable typed code

18 min read typescript
Course contents (16 lessons)
  1. Getting started
  2. Why TypeScript? What it is and what it is not
  3. Setting up TypeScript: tsc and tsconfig.json
  4. Core types
  5. Basic types: primitives, arrays, tuples, any and unknown
  6. Typing functions: parameters, returns, optionals and overloads
  7. Objects, interfaces and type aliases
  8. Unions, literals and enums
  9. Union types and type narrowing
  10. Literal types, enums and as const
  11. Classes and generics
  12. Classes in TypeScript
  13. Generics: writing reusable typed code
  14. Built-in utility types: Partial, Pick, Omit, Record and more
  15. Advanced types
  16. Mapped and conditional types
  17. Modules, type imports and declaration files
  18. TypeScript in real projects
  19. Typing async code and API responses
  20. Strict mode and compiler flags that matter
  21. Migrating a JavaScript project to TypeScript
  22. Final project: a type-safe task manager

The problem generics solve

Imagine a function that returns the first item of an array. For numbers it should return a number. For strings, a string. Without generics you have two bad choices: write a copy per type, or use any and lose the type.

function firstNumber(items: number[]): number | undefined { return items[0]; }
function firstString(items: string[]): string | undefined { return items[0]; }
function firstAny(items: any[]): any { return items[0]; }   // loses type information

A generic is a function, class or type with a placeholder for a type. You fill in the placeholder when you use it. Think of it as a parameter for a type.

A generic function

function first<T>(items: T[]): T | undefined {
  return items[0];
}

const n = first([10, 20, 30]);        // n is number | undefined
const s = first(["a", "b"]);          // s is string | undefined
const none = first([]);               // none is undefined

console.log(n, s, none);

if (n !== undefined) {
  console.log(n.toFixed(1));          // TypeScript knows it is a number
}

<T> declares the type parameter. The name T is a convention, but any name works, and a longer name helps with several parameters. When you call first([10, 20, 30]), TypeScript infers T as number from the argument. You rarely write the type by hand, but you can: first<number>([1, 2]).

The return type is T | undefined, which says "an item of whatever type the array holds, or nothing". The result keeps its exact type, which any could never do.

Multiple type parameters

function pair<A, B>(a: A, b: B): [A, B] {
  return [a, b];
}

const p = pair("age", 28);   // [string, number]
console.log(p[0].toUpperCase(), p[1] + 1);

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

const lengths = mapValues(["one", "three"], s => s.length);  // number[]
console.log(lengths);

In mapValues, T comes from the array and U from what the callback returns. This is exactly how Array.prototype.map is typed.

Constraints with extends

Sometimes a generic needs to know a little about its type. If you write function longest<T>(a: T, b: T) { return a.length > b.length ? a : b }, the compiler stops you: not every T has .length. Add a constraint:

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

console.log(longest("hello", "hi"));          // "hello"
console.log(longest([1, 2, 3], [4, 5]));      // [1, 2, 3]
// longest(10, 20);   // Error: number has no 'length'

T extends { length: number } means "any type that has at least a numeric length". Strings and arrays qualify, and the return type keeps the exact type you passed in.

keyof and property access

A very useful combination is keyof, which gives the union of an object's key names:

function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const user = { id: 1, name: "Sara", active: true };

const name = getProperty(user, "name");     // string
const active = getProperty(user, "active"); // boolean
console.log(name.toUpperCase(), active);
// getProperty(user, "email");  // Error: "email" is not a key of user

K extends keyof T limits the key to real property names, and T[K] is the type of that property, called an indexed access type. The result type changes with the key you pass. This is something plain types cannot express.

Generic interfaces and types

interface ApiResponse<T> {
  data: T;
  status: number;
  error?: string;
}

interface User { id: number; name: string }

const response: ApiResponse<User> = {
  data: { id: 1, name: "Ali" },
  status: 200,
};

const list: ApiResponse<User[]> = { data: [], status: 200 };
console.log(response.data.name, list.data.length);

One definition serves every kind of response. You will use this pattern for API wrappers in a later lesson.

Generic classes

class Stack<T> {
  private items: T[] = [];

  push(item: T): void {
    this.items.push(item);
  }

  pop(): T | undefined {
    return this.items.pop();
  }

  peek(): T | undefined {
    return this.items[this.items.length - 1];
  }

  get size(): number {
    return this.items.length;
  }
}

const numbers = new Stack<number>();
numbers.push(1);
numbers.push(2);
console.log(numbers.pop(), numbers.size);   // 2 1
// numbers.push("three");   // Error

const words = new Stack<string>();
words.push("a");
console.log(words.peek());

For a class, you usually give the type when you create it: new Stack<number>(). The same class safely holds numbers in one place and strings in another.

Default type parameters

interface Box<T = string> {
  value: T;
}

const a: Box = { value: "text" };          // T defaults to string
const b: Box<number> = { value: 5 };
console.log(a.value, b.value);

When not to use generics

A generic must earn its place. If a type parameter appears only once in a signature, it is usually not doing anything. For example function log<T>(value: T): void is the same as function log(value: unknown): void. A good test: every T should connect at least two things, such as input and output, or two arguments. Over-generic code is harder to read than the repeated code it replaced.

Common mistakes

  • **Using any when a generic would keep the type.** If the output type depends on the input type, you want a generic.
  • Forgetting the constraint. Using .length or other members on an unconstrained T is an error.
  • A type parameter that is used only once. It adds noise.
  • Writing the type argument when inference would work. first<number>([1, 2]) is noise.
  • **Naming everything T.** With three parameters, use TInput, TOutput or similar.
  • Casting inside generic functions to make errors go away. It usually means the signature is wrong.

Try it yourself

  1. Write last<T>(items: T[]): T | undefined.
  2. Write groupBy<T, K extends string>(items: T[], getKey: (item: T) => K): Record<K, T[]>. Hint: start with an empty object cast to the result type, and fill it in a loop.
  3. Add isEmpty() and toArray() methods to the Stack class.
  4. Write pluck<T, K extends keyof T>(items: T[], key: K): T[K][] that extracts one property from every object in an array.
typescript
function first<T>(items: T[]): T | undefined {
  return items[0];
}

const n = first([10, 20, 30]);        // n is number | undefined
const s = first(["a", "b"]);          // s is string | undefined
const none = first([]);               // none is undefined

console.log(n, s, none);

if (n !== undefined) {
  console.log(n.toFixed(1));          // TypeScript knows it is a number
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account