Course contentsShow
← TypeScript
Lesson 577 of 1,79614. Generics in PracticeFree lesson

Generic Container Types (Array, Set, Map)

How generics power built-in collections and why they need type parameters to be useful.

Generic Container Types (Array, Set, Map)

You'll learn: How generics power JavaScript's built-in collections and why type parameters make them type-safe and useful.

Why Container Types Need Generics

TypeScript's built-in collections like Array, Set, and Map are generic by design. Without type parameters, these containers would have no way to track what they hold. An Array without generics would just store any, losing all type safety when you retrieve items.

Generics let you declare what kind of data lives inside these containers, turning them from "boxes that hold anything" into "boxes that hold specific things."

How Generics Power Collections

Array<T>

Arrays use a type parameter to track element types:

const numbers: Array<number> = [1, 2, 3];
const strings: string[] = ["a", "b"]; // same as Array<string>

Set<T>

Sets store unique values with a type parameter:

const tags: Set<string> = new Set(["typescript", "generics"]);
tags.add("learning"); // ✓ string allowed
// tags.add(42); // ✗ number not allowed

Map<K, V>

Maps use two type parameters—one for keys, one for values:

const scores: Map<string, number> = new Map();
scores.set("Alice", 95); // ✓ string key, number value
// scores.set(123, "Bob"); // ✗ wrong types

Why Type Parameters Are Essential

Without generics, retrieving items would return any, forcing you to manually check types everywhere. With generics, TypeScript knows exactly what comes out matches what went in—your methods like .get(), .has(), and array indexing all return properly typed values.

Key Takeaway: Built-in collections like Array, Set, and Map are generic containers—they use type parameters to remember and enforce what types of data they store, giving you autocomplete and safety when adding or retrieving items.