So I'm trying to create an utils function that works like _.pick()
function from Lodash, but using TypeScript. Basically it is an utils function that would return an object with selected properties, where the first param is the object target and the second param is the array of object properties string that can be chosen based on the object in the first param.
I have found and applied the function (source) and it's working fine, but I'm kind of confused on how to apply the types so it works just like using the original library.
const pick = (object: { [key: string]: any }, keys: string[]) => {
return keys.reduce<any>((obj, key) => {
if (object && Object.prototype.hasOwnProperty.call(object, key)) {
obj[key as keyof typeof obj] = object[key];
}
return obj;
}, {});
};
export default pick;
Use case:
const object = { 'a': 1, 'b': '2', 'c': 3 };
const pickedObject = pick(object, ['a', 'c']);
console.log(pickedObject)// => { 'a': 1, 'c': 3 }
This is the function I'm currently using and I'm expecting the second params would have type of array of object properties string based on the object in first param, and the return type would be the object with properties that is chosen from the second param.