Generics

suggest change

Generics preserve relationships between types. Add constraints when an implementation needs particular members.

interface HasId {
  readonly id: string;
}

function indexById<T extends HasId>(items: readonly T[]): Map<string, T> {
  return new Map(items.map(item => [item.id, item]));
}

interface User extends HasId {
  name: string;
}

const users: User[] = [{ id: "1", name: "Ada" }];
const byId = indexById(users);
console.log(byId.get("1")?.name);

Prefer inference at call sites. Supply type arguments explicitly only when inference lacks enough information.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents