Build a dictionary from an array using a key selector. Constrain the key’s type with K extends PropertyKey so it can be used as an object key (string | number | symbol). Return a Record<K, T> so callers get precise value types.
When two items produce the same key, let the later one win. Keep the function pure by creating a new object.
function byId<T>(items: T[], getId: (t: T) => string) {
/* ... */
}
Create a map from keys to items.