Skip to content
AgileLogics
5 min read

Advanced Generics

Prerequisites: Generics

A generic can be constrained to only accept types with certain properties, using extends.

interface HasId {
    id: number;
}

function findById<T extends HasId>(items: T[], id: number): T | undefined {
    return items.find((item) => item.id === id);
}

T extends HasId means "T can be anything, as long as it has at least an id: number property" — this lets findById work with any shape that includes an id, while still safely accessing .id inside the function.