Lesson 7 of 11 · 11 min

Generics

Suppose you want a function that returns the last item of a list. With any, you lose all type information:

function last(items: any[]): any {
  return items[items.length - 1];
}
const n = last([1, 2, 3]);   // n is 'any': TypeScript can no longer help you

A generic function takes a type parameter, written in angle brackets, and uses it like a variable for types:

function last<T>(items: T[]): T | undefined {
  return items[items.length - 1];
}

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

TypeScript works out T from what you pass in. The function works for every type, and each call keeps its exact type.

Several type parameters and constraints

You can have more than one type parameter, and constrain one with extends to say what it must be:

function pluck<T, K extends keyof T>(item: T, key: K): T[K] {
  return item[key];
}
pluck({ name: "Ana", age: 30 }, "age");    // number
pluck({ name: "Ana", age: 30 }, "email");  // error: not a key of the object

Record<K, V> is a built-in generic type for "an object whose keys are K and values are V".

Your task

  1. first<T>(items: T[]): T | undefined: the first item, or undefined for an empty list.
  2. groupBy<T, K extends string>(items: T[], key: (item: T) => K): Record<K, T[]>: puts items into lists by the key the function returns.
main.ts
function first(items: any[]): any {
  return items[0];
}

function groupBy(items: any[], key: any): any {
  return {};
}

const n: number | undefined = first([10, 20]);
console.log(n);

TypeScript 5.9 runs right here in your browser. The first run downloads about 1.5 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…