Skip to main content
Module 3 · Lesson 2 of 26/22 in the course~18 min
Module lessons (2/2)

Fundamental Generics

Lesson preview6 hands-on exercises readyCourse TypeScript · Module 3 — Generics and Functions

Write generic functions, interfaces, and classes with compile-time safe extends keyof T constraints.

What you'll learn in this lesson

  • Understand why any destroys the relationship between input and output while Generics (<T>) preserves it.
  • Let the compiler infer arguments of type <T> from the values passed to the call.
  • Apply constraints (<T extends { length: number }>) and K extends keyof T to read properties safely.
  • Parameterize interfaces (Box<T>, Pair<T, U>, ApiResult<T>) for containers and asynchronous responses.

Overview

Without generics you would have two poor choices: duplicate the same function for string, number and User, or use any losing autocompletion on the return value. A generic type parameter (<T>) captures the actual type provided by the caller and carries it exactly to the result.

Inside a generic function <T>, TypeScript assumes that T can be any type, so it prohibits access to .length or arbitrary properties until you declare a constraint (extends).

Sections covered in this lesson

  1. 1Generic Functions and Interfaces
  2. 2Constraints with extends and K extends keyof T
  3. 3Guided practice
  4. 4Check for understanding
Pro Lesson · Module 3 — Generics and Functions

Unlock "Fundamental Generics" and the full Course TypeScript curriculum

Write generic functions, interfaces, and classes with compile-time safe extends keyof T constraints.

Unlock all 6 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Course TypeScript plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.