Create your own 'objectKeys' function using generics and the 'keyof' operator

The looseness of Object.keys can be a real pain point when using TypeScript. Luckily, it's pretty simple to create a tighter version using generics and the keyof operator.

Discuss on Twitter

Transcript

A common pain point when using TypeScript is when you have this object.keys function here. MyObject here has keys A, B, and C, but when I try to iterate over its keys when I've extracted them from object.keys, then the key is typed as a string. That means that when I try to access it, I get this horrible long type error, "No index signature with parameter of type 'string' was found in type A, B, C."

This should be typed as key of myObject. The way to get around this is to create your own object.keys function, so object.keys=. We're going to have Obj, which is our object. We're going to add that to the generics list here. Then we're going to return a keyof Obj, and that is going to be in an array like this.

Here, "A function whose declared type is neither 'void'...and must return a value." We just need to return Object.keys(obj) as...Yeah, we can do this instead. Now, if we go object.keys(myObject), then key is typed as A, B, or C.

More Tips