Exploring a stricter definition of the Object.keys
function using mapped types in TypeScript.
An Illustrative Example:
To begin, consider an object defined using const
:
const myObj = {
a: 'some value',
b: 5
};
Typically, when utilizing Object.keys
on this object, the resulting type would be string[]
const keysOfMyObj = Object.keys(myObj); // `const keysOfMyObj: string[]`
The Query at Hand:
However, let's delve into making this return type more precise. Instead of a generic array like string[]
, I aim for Object.keys
to yield ("a" | "b")[]
.
Aiming For This Type:
const newKeysOfMyObj = myKeys(myObj); // `const newKeysOfMyObj: ("a" | "b")[]`
Attempting Solutions:
I believe achieving this objective involves leveraging mapped types in TypeScript.
To start, I define a type that guarantees an object's values align with its keys:
type Keys<T> = {
[P in keyof T]: P;
};
let myObjKeysOnly: Keys<typeof myObj>;
// resultant type:
//
// let myObjKeysOnly: {
// a: "a";
// b: "b";
// }
//
One approach involves constructing a custom function that acts as a typed wrapper around Object.keys
:
function myKeys<T>(obj: T) {
return Object.keys(obj) as (Keys<T>);
}
Open to suggestions and ideas! Feel free to share your insights.