How to extract the following pipe operator to a generic function
.pipe(map((products: IProduct[]) => products.map((product: IProduct) => product.title)));
Compare to this answer I tried a generic variant:
static mapPropertiesToArray<T extends object>( property: string ){
return pipe(map((objects: T[]) => objects.map((item: T) => item[property as keyof T])));
}
Rather than casting
property, define it as a key of T. Also,pipe()is unnecessary since you're not combining operators:This ensures a use like
of(myArray).pipe(mapPropertiesToArray('title'))throws an error iftitleisn't a valid attributeEdit: your comment made me realize this would return a union type if T's keys' values have differing types. We need slightly more precise typing: