I have the following Typescript class:

export class Envelope<T> {
  result: T;
  constructor(result: T) {
    this.result = result;
  }
}

I need to map Envelope<RecentPostResponse[]> to Observable<PostModel[]>:

getPosts(): Observable<PostModel[]> {

  return this.postService.getRecent().pipe(

    map((envelope: Envelope<RecentPostResponse[]>) => 

    envelope.result.map((response: RecentPostResponse) => { 

      return {
        id: response.id, 
        // Other properties
      };

    })));

But I am getting the error:

Argument of type 'OperatorFunction<Envelope<RecentPostResponse[]>, { id: number; }[]>'.
Type 'Envelope<RecentPostResponse[]>' is not assignable to type 'Envelope<RecentPostResponse>'.

What am I missing?

Update

Initially the envelope was (result type was T[]):

export class Envelope<T> {
  result: T[];
  constructor(result: T[]) {
    this.result = result;
  }
}

And the conversion was working as:

getPosts(): Observable<PostModel[]> {

  return this.postService.getRecent().pipe(

    map((envelope: Envelope<RecentPostResponse>) => 

      envelope.result.map((response: RecentePostResponse) => { 

        return {
          id: response.id, 
        };

      }))); 

    };

Then I did a simple change to Envelope (result type changed from T[] to T):

export class Envelope<T> {
  result: T;
  constructor(result: T) {
    this.result = result;
  }
}

But I am failing to adapt the conversion to it ...

1 Answers

1
Mr.Sarunov On

You are not actually defining the result type.

This is the type definition of map:

export declare function map<T, R>(
  project: (value: T, index: number
) => R, thisArg?: any): OperatorFunction<T, R>;

This is how you can use it:

Observable<PostModel[]> this.postService.getRecent().pipe(

  map<Envelope<T1>,Envelope<T2>>((envelope: Envelope<RecentPostResponse[]>) => 

  return envelope.result.map<T1,T2>((response: RecentPostResponse) => { 

    return {
      id: response.id, 
      // Other properties
    };

  })));