Read Object Keys Without Losing Their Types

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

The problem

  • medium
  • Code

Object.keys returns string[], and indexing an object with a plain string is a type error. Export a type StringKeys<T>, the string keys of T, and write keysOf(obj), returning obj's own keys in order typed as StringKeys of obj in an array, and hasKey(obj, key), which is true only when key is one of obj's own keys (not an inherited one like toString). Make hasKey a type guard, so that after if (hasKey(obj, key)) a string key is narrowed to obj's keys and obj[key] compiles.

Your code must pass

  • keysOf lists own keys in order
  • hasKey is true for own keys only
  • Has no type errors
  • keysOf returns the object's own key names
  • hasKey narrows the key