Transform array of elements from type T1 to element in the array to type T2

Here is a Typescript class I am working with:

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

I'm trying to convert

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

    })));

However, I encounter the following error:

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

What am I missing?

Update:

The original envelope had its result type as an array (result type was T[]):

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

Initially, the conversion was working as expected:

getPosts(): Observable<PostModel[]> {

  return this.postService.getRecent().pipe(

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

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

        return {
          id: response.id, 
        };

      }))); 

    };

Then I made a change to Envelope where the result type changed from T[] to T:

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

But now I am struggling to modify the conversion accordingly...

Answer №1

You haven't explicitly specified the type of result here.

Below is the definition for the map function:

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

Here's an example of how to 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
    };

  })));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sharing API data between components in Angular 5

Summary: I'm trying to retrieve data from an input field in a component form, then compare it using API services. After that, I want to take the value from the "correo" field in the form and pass it to another component. In this other component, I aim ...

"Error encountered: 'Callable function cannot be invoked on Mongoose model

In my Nest JS service, the code structure is as follows: import { Injectable } from '@nestjs/common'; import { Model } from 'mongoose'; import { InjectModel } from '@nestjs/mongoose'; import { Collection } from './inter ...

Choose an alternative following the start-up phase

I have been searching for solutions on various platforms, including Stack Overflow, but nothing seems to work for me. I am struggling with selecting the first option after initializing the box because currently it is choosing a blank option that is not eve ...

Using a reactive form in Angular 12, the selected form group is initialized with an empty array

.html File <div *ngFor="let analysis of analysisFormArray.controls; let i = index" [class.selected]="analysis === selectedAnalysis"> <div [formGroup]="analysis" (click)="onSelect(analysis)"> ...

Why will the experimental activation of React concurrent features in Nextjs 12 disable API routes?

I just upgraded to Next.js version 12 and set up some API routes (e.g. "/api/products"). These routes were functioning properly, but when I enabled concurrentFeatures: true in my next.config.ts, the API routes stopped working. The console display ...

The React namespace is missing the exported member 'InputHTMLAttributes', and the MenuItemProps interface is incorrectly extending the ListItemProps interface

I am currently working with Material-UI and typescript. I have installed the typescript types using npm install -D @types/material-ui. After loading my webpage, I encountered the following errors: ERROR in [at-loader] ./node_modules/@types/material ...

Encountering a build error in ng serve right after running npm install

After deleting the node_modules directory and rebuilding it with npm install, I encountered an error in my angular2 app when using cmd ng serve. Error: 'common-tags' module not found at Function.Module._resolveFilename (module.js:337:15) ...

Angular 6 Error: Unable to access property 'e4b7...f' as it is undefined

I'm encountering an issue while trying to initialize an object based on a TypeScript interface. Even though I am assigning a value, I still receive an error stating that the property is undefined. interface ITableData { domainObjectName: string; ...

Guide on setting up an AWS code pipeline for Elastic Beanstalk deployment on ASP.NET Core 5.0 with Angular

I am facing a challenge with deploying my ASP.NET Core 5.0 application with Angular to the EBS Windows environment using AWS CodePipeline (CI / CD). Despite searching various internet resources for solutions, I have not been able to find much help. My att ...

What is the best way to retrieve an object when a value is not found? Consider implementing a looping mechanism with a specific condition in React and TypeScript to successfully

Greetings, I am faced with an array of objects structured as follows: const arr_obj = [ { id: '1', jobs: [ { completed: false, id: '11', run: { ...

What is the process for integrating additional Firebase Cloud Functions into an Angular Universal project?

When working on an Angular Universal project, the fixed configuration for firebase.json looks like this: { "hosting": [{ "target": "PROJECT-ID", "public": "dist/PROJECT-ID/dist/PROJECT-ID/bro ...

How to use Angular 7 to send a JSON object as a parameter in an HTTP GET

I am attempting to send a JSON structure to a REST service from Angular in this manner: let test5var = { "test5var1": { "test5var2": "0317", "test5var3": "9556" }, ...

Tips for inserting an object into an array

Here's the data I received: { 0:{modifierId: 4, modifierName: 'Garlic', modifierPrice: 60 } 1:{modifierId: 1, modifierName: 'Tartar ', modifierPrice: 60} 2:{modifierId: 3, modifierName: 'Herb ', modifierPrice: 60} item ...

Navigating with Angular 2 router while authenticating with AngularFire2

Currently, I am working on a route where I need to wait for the auth object from Firebase before proceeding. Below is the code snippet that I have implemented: Route { path: 'random', component: RandomComponent, resolve: { auth: AuthServi ...

Angular 2- Unable to bind to 'ngSwitchCase' as it is not recognized as a native property

I am facing an issue with my code where I have two lists that are displayed in my .html file. In order to avoid repetition, I decided to utilize ngSwitch. However, when I try to implement this approach, I encounter an error. Here is the snippet of code cau ...

Global Enum in Typescript that is Optimized for Inlining during Compilation

I'm facing a challenge with an enum that is widely used in my project. Having to import it into every file is becoming cumbersome. Is there a way to define the enum in the .d.ts file so that it automatically gets included when compiled to Javascript? ...

Is there a way for the parent class to access the child class in Angular 2?

Seeking guidance on accessing a child class from a parent class in my Angular 2 application with Typescript. The structure of the parent and child classes are as follows: The parent class, AllDataPageComponent: @Component({ selector: 'all-data-p ...

Navigating Mixins in Ember CLI Typescript

I'm curious about the best approach for handling mixins in a typed Ember application. While removing mixins from the application is ideal, many addons do not yet support TypeScript. So, how can we effectively utilize Ember Simple Auth's applicati ...

How to activate a textbox in Angular 6 when a checkbox is selected:

Looking for examples related to this topic, all I've come across are AngularJs examples. Is there a way to enable my textbox based on the status of a checkbox in the same row, without directly binding them through a boolean value or using JavaScript? ...

Accessing Child Properties in Parent Component using Typescript

New to the world of Typescript! Imagine having a component called TitleSubtitle that consists of both a Title and a Subtitle component. The Title component comes with props: interface TitleProps { text: string; } The Subtitle component also has props ...