rxjsrxjs-observablesrxjs-pipeable-operators

Extract pipeable operator as generic function in RXJS


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])));
}

Solution

  • Rather than casting property, define it as a key of T. Also, pipe() is unnecessary since you're not combining operators:

    function mapPropertiesToArray<T>(property: keyof T) {
      return map((objects: T[]) => objects.map((item: T) => item[property]));
    }
    

    This ensures a use like of(myArray).pipe(mapPropertiesToArray('title')) throws an error if title isn't a valid attribute

    Edit: 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:

    function mapPropertiesToArray<T, P extends keyof T>(property: P) {
      return map((objects: T[]) => objects.map(item => item[property]));
    }