Codington
0 of 5 problems solved0%

Generics Fundamentals

5 exercises

Generics let you write components that work over many types without losing type safety:

function identity<T>(value: T): T { return value; } const num = identity(42); // T is number const str = identity("hello"); // T is string

A type parameter like T is a placeholder for a concrete type that callers supply or TypeScript infers.

Key generic patterns:

Constraints – Require certain properties:

function getLength<T extends { length: number }>(value: T) { return value.length; // Safe! We know T has length }

Related type parameters – Link keys to objects:

function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; // Return type matches the property type }

Generic types and classes:

type Box<T> = { value: T }; class Stack<T> { /* ... */ }

In this category, you'll:

  • Write generic functions that preserve type relationships
  • Add constraints with extends to require specific properties
  • Use keyof and indexed access for safe property lookups
  • Create generic types and classes
  • Understand when and why to use generics

Note: Type arguments are erased at runtime, so implementations rely on normal JavaScript while types keep the API safe.

CodingtonCodington

© 2025 Codington. Built with TypeScript, TanStack Start and a lot of console.log().