Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 4.2Generics

Why generics

Generics let one implementation preserve the type supplied by its caller. They are safer than any because the relationship between input and output is retained.

TypeScript
function first<T>(values: T[]): T | undefined {
  return values[0];
}

const name = first(["Ada", "Lin"]);

Constraints

A constraint states the minimum shape a generic value must have. For example, T extends { id: number } permits code to use id while allowing richer objects.

Feedback 👍
Comments are sent via email to me.