Skip to article content
FrontendXLesson 07 / 40

Generics and constraints

Go from the first annotated variable to writing your own conditional, mapped and infer-based utility types, while keeping a clear line between compile-time checking and runtime behavior.

intermediate · about 45 minutes · 4 exercises

  • Predict
  • Implement
  • Debug

What you will be able to do

#
  • Write a generic function that infers its type argument.
  • Constrain a type parameter with extends.
  • Use a keyof constraint to read a property safely.

Overview

#

Type parameters

A generic function carries a type variable instead of a fixed type.

snippet.ts
function first<T>(items: readonly T[]): T | undefined {
  return items[0];
}

The caller usually does not write <T>; the checker infers it from the argument.

Constraints

T extends U limits what T can be, which unlocks member access.

snippet.ts
function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}

keyof constraints

To read a property by name, constrain the key to the object's keys.

snippet.ts
function pluck<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

The return type T[K] is an indexed access type: the type of the property named K.

Defaults

A type parameter can have a default: function make<T = string>(). Defaults are used only when the argument cannot be inferred.

Generic arrows

In a .tsx file an arrow generic needs a trailing comma or an extends clause to avoid being read as JSX: <T,>(x: T) => x.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Implement

    Implement `last<T>(items: readonly T[]): T | undefined` returning the final element or undefined.

    starter.typescript
    export function last<T>(items: readonly T[]): T | undefined {
      // your code
    }
    

    Reveal the reference answer
    reference.typescript
    export function last<T>(items: readonly T[]): T | undefined {
      return items[items.length - 1];
    }
    

    Authored expected output: Compiles with no errors. Runtime: last([1, 2, 3]) is 3, last([]) is undefined.

    The generic preserves the element type instead of widening to unknown.

  2. Exercise 2Implement

    Implement `pluck<T, K extends keyof T>(obj: T, key: K): T[K]` that returns the property value.

    starter.typescript
    export function pluck<T, K extends keyof T>(obj: T, key: K): T[K] {
      // your code
    }
    

    Reveal the reference answer
    reference.typescript
    export function pluck<T, K extends keyof T>(obj: T, key: K): T[K] {
      return obj[key];
    }
    

    Authored expected output: Compiles with no errors. Runtime: pluck({ a: 1, b: "x" }, "b") is "x". The call pluck({ a: 1 }, "z") fails to compile.

    The keyof constraint rejects unknown keys at compile time and the indexed access types the result.

  3. Exercise 3Predict

    What type does TypeScript infer for `result`? ```ts function id<T>(value: T): T { return value; } const result = id("hello"); ```

    Choose the best answer
  4. Exercise 4Debug

    This fails to compile because T is unconstrained. Fix it so the body is valid. ```ts function size<T>(items: T): number { return items.length; } ```

    starter.typescript
    function size<T>(items: T): number {
      return items.length;
    }
    

    Reveal the reference answer
    reference.typescript
    function size<T extends { length: number }>(items: T): number {
      return items.length;
    }
    

    Authored expected output: Compile error resolved: Property 'length' does not exist on type 'T'. The constraint makes length available.

    A constraint tells the checker which members T is guaranteed to have.

Common misconceptions

#
  • Generics are only for classes.
  • A type parameter is a runtime value.
  • You must always pass the type argument explicitly.

Follow-up practice

#
  • typescript-utility-types

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.