Generics
suggest changeGenerics 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents