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

A common pain point when using TypeScript is when you have this Object.keys function here. My object here has keys a b and c but when I try to iterate over its keys when I've extracted them from Object.keys, 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.

So this really should be typed as keyof myObject and the way to get around this is to create your own Object.keys function.

So we'll create our function objectKeys which has a generic Obj. We'll set that as the type for our argument obj and then set the return type to be an array of keyof Obj.

Then we'll return Object.keys(obj) as (keyof Obj)[]. We are using the as to make a type assertion. This tells the compiler to infer the result of Object.keys(obj) to be an array of the objects keys as strings.

So now if we go objectKeys(myObject) then key is typed as a b or c.

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.

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

More Tips