Index a List by a Computed Key

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code

Write keyBy(items, keyOf): return an object mapping each item's key (what keyOf returns) to the item, where a later item with the same key replaces an earlier one. Type it as a Record whose keys are exactly what keyOf returns (keying countries by a code of "GB" | "FR" gives just those two keys) and whose values have the items' type, and reject a keyOf that returns something that can't be a key.

Your code must pass

  • Indexes each item by its key
  • A later item replaces an earlier one with the same key
  • Has no type errors
  • Keys are what keyOf returns
  • Values are the items' type
  • Rejects a key that can't be an object key