Introduction
Data structures do not care what they hold: a queue of jobs works exactly like a queue of numbers. A generic class is written once with a type parameter, and every object made from it is checked for its own item type. This lesson builds generic classes and introduces the typed collections that come with JavaScript: Map, Set and readonly arrays.
How it works
A class takes type parameters after its name, and its fields and methods use them:
class Queue<T> {
private items: T[] = [];
enqueue(item: T): void { this.items.push(item); }
dequeue(): T | undefined { return this.items.shift(); }
}
const jobs = new Queue<string>();
jobs.enqueue(42); // error: number is not assignable to string
The type argument is given when the object is made, or inferred from constructor arguments. Interfaces and type aliases can be generic too, and a type parameter can have a default: interface Result<T, E = string> lets you write Result<number> when errors are strings.
JavaScript's collections are generic in TypeScript:
Map<K, V>stores key-value pairs. Keys can be any type, not only strings, and iteration follows insertion order.getreturnsV | undefined, because the key may be missing.Set<T>stores distinct values;has,addanddeleteare checked againstT.ReadonlyArray<T>, also writtenreadonly T[], has nopush,poporsort. A function that takesreadonly number[]promises the caller not to change their array.
For keyed data you now have three options. Use an object type when the keys are fixed and known ({ name: string; age: number }), a Record<string, T> for a simple dictionary that will be turned into JSON, and a Map<K, V> when keys are not strings, when entries are added and removed often, or when insertion order matters.
Example
// A generic class, a generic interface with a default, and the built-in Map and Set.
class Queue<T> {
private items: T[] = [];
enqueue(item: T): void {
this.items.push(item);
}
dequeue(): T | undefined {
return this.items.shift();
}
get size(): number {
return this.items.length;
}
}
interface Result<T, E = string> {
ok: boolean;
value?: T;
error?: E;
}
const jobs = new Queue<string>();
jobs.enqueue("build");
jobs.enqueue("test");
const next = jobs.dequeue();
console.log(next, jobs.size);
const counts = new Map<string, number>();
for (const word of ["to", "be", "or", "not", "to", "be"]) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
const unique = new Set<string>(counts.keys());
const missing: Result<number> = { ok: false, error: "not found" };
console.log(counts, unique.size, missing);Line by line
Queue<T>stores items of type T and returns them fromdequeue, or undefined when empty.Result<T, E = string>has a default for its error type, soResult<number>is complete.jobsis a queue of strings:dequeuegives back"build"first.countsis aMap<string, number>;getmay give undefined, so?? 0supplies the start.uniqueis aSet<string>made from the map's keys.
Expected result
build 1
Map(4) { 'to' => 2, 'be' => 2, 'or' => 1, 'not' => 1 } 4 { ok: false, error: 'not found' }
In the real world
Libraries ship generic data structures: caches, event emitters typed by event name, state stores typed by their state. Framework APIs such as useState<T> and EventEmitter<Events> are generic so that your own types flow through them. Maps are the usual choice for in-memory caches and indexes, where keys come and go.
Common mistakes
- Making a field generic that does not need to be, which complicates every use of the class.
- Forgetting that Map.get may return undefined and using the result directly.
- Using an object as a dictionary with arbitrary keys, where keys such as "constructor" or "proto" behave strangely; a Map has no such surprises.
- Expecting readonly arrays to be frozen at run time: readonly is a compile-time promise.
Best practices
- Write a generic class when the same structure is needed for several item types.
- Use
readonly T[]for parameters a function only reads. - Prefer
Mapfor dynamic keys andSetfor membership tests over arrays withincludes.
Summary
Generic classes and interfaces take type parameters, with optional defaults, and keep the item type through every method. Map<K, V>, Set<T> and ReadonlyArray<T> are typed collections: maps for any keys in insertion order, sets for distinct values, and readonly arrays for data a function promises not to change.
Quick check
Key takeaways
- A generic class keeps the item type through every method: a Queue of strings gives back strings.
- Map and Set take type arguments and check every key, value and item.
- readonly arrays let a function promise not to change what it is given.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.