Generic function with a constraint
T extends HasId lets findById accept any object that has a numeric id while keeping the full element type in the return value.
interface HasId {
id: number;
}
function findById<T extends HasId>(items: T[], id: number): T | undefined {
return items.find((item) => item.id === id);
}
const users = [
{ id: 1, name: "Ada" },
{ id: 2, name: "Linus" },
];
console.log(findById(users, 2)?.name); // "Linus"