将T1类型的数组映射到T2类型的数组

时间:2019-05-13 12:27:34

标签: angular typescript rxjs

我有以下Typescript类:

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

我需要将Envelope<RecentPostResponse[]>映射到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
      };

    })));

但是我得到了错误:

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

我想念什么?

更新

最初的信封是(result type was T[]):

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

该转换的工作方式为:

getPosts(): Observable<PostModel[]> {

  return this.postService.getRecent().pipe(

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

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

        return {
          id: response.id, 
        };

      }))); 

    };

然后我对信封(result type changed from T[] to T)进行了简单的更改:

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

但是我无法适应转换...

1 个答案:

答案 0 :(得分:1)

您实际上并没有定义结果类型。

这是map的类型定义:

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

这是您可以使用的方式:

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

  })));