I am currently working on implementing a function called sumPluck. This function will allow the user to specify a property of type number from an object in an array, and then calculate the sum of all those properties.
For example:
type A = { prop: number }
const arr: A[] = [{prop: 1}, {prop: 2}];
pluckSum("prop", arr); // 3
I have a basic idea of how to extract the specified property, but I'm having trouble ensuring that the property is definitely a number. Here's what I have so far:
type PropertiesOfTypeNames<T, U> = { [K in keyof T]: T[K] extends U ? K : never }[keyof T];
type PropertiesOfType<T, U> = Pick<T, PropertiesOfTypeNames<T, U>>;
type NumberProperties<T> = PropertiesOfType<T, number>;
const pluckSum = <T, K extends keyof NumberProperties<T>>(arr: T[], k: K) =>
pipe(
arr,
R.map(v => v[k]),
R.sum
);
An error is being displayed under the map function stating: Type 'T[string]' cannot be assigned to type 'number'
It seems like the mapped type does not properly indicate that v[k] is indeed a number property. I might be missing something in my approach here.