TypeScript – A polyfill to extend the Object class to add a values property to complement the keys property

I expect you’ve used Object.keys at some point. Here is how to extend the Object class to add a values property. This kind of thing is useful when you have a lookup of keys where all of the values are the same type, such as the following object you’d expect to see in a Redux app.

{
"gb": { code: "gb", name: "Great Britain" },
"us": { code: "us", name: "United States" }
}

The code

interface ObjectConstructor {
values<T>(source: any): T[];
}

/**
* Extends the Object class to convert a name:value object to an array of value
* @param source
* @returns {T[]}
*/
Object.values = function<T>(source: any): T[] {
const result = Object.keys(source)
.map(x => source[x]);
return result;
}

Comments

Leave a Reply

Your email address will not be published.