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

The parameter value in Angular routes is substituted with the parameter name in the AuthGuard's canLoad method

Within my AuthGuardService, I have a function called canLoad that accepts a parameter of type Route. In this function, I set the authentication redirect URL to the path property of the Route parameter. An issue arises when the path contains a route parame ...

Prevent the onclick function of a span element from being triggered when the user clicks on a dropdown menu contained within

Just delving into the world of web development and currently tackling a React project. Encountered an issue where I need to make a span element clickable. However, there's a dropdown within that span that doesn't have any onClick event attached t ...

Creating multiple copies of a form div in Angular using Typescript

I'm attempting to replicate a form using Angular, but I keep getting the error message "Object is possibly 'null'". HTML: <div class="form-container"> <form class="example"> <mat-form-field> ...

Having trouble pushing to an array in Angular typescript? It seems to be returning as undefined

As a newcomer to Angular with a basic understanding of JavaScript, I am attempting to create a program that can solve Sudoku puzzles. In a 9x9 grid, there are a total of 81 points or squares. To efficiently check for violations of Sudoku rules - no repeati ...

The specified path "/src/app/app.module.ts" was not found while attempting to add ng in an Angular project that is using a custom path

I encountered an issue while attempting to integrate Angular Universal into my project. Here is my folder structure: src main app app.module.ts node_modules tsconfig.json My project uses Angular version 15.2.5 and the latest version of Angular Uni ...

The object returned by bodyParser is not a string but a data structure

I have been working on implementing a JSON content listener in Typescript using Express and Body-parser. Everything is functioning perfectly, except when I receive the JSON webhook, it is logged as an object instead of a string. import express from 'e ...

The Nextjs next-auth implementation with URL '/api/auth/callback/cognito' encountered a 502 Bad Gateway error while in production

I'm facing a challenge while trying to deploy a nextjs app that utilizes 'next-auth' with AWS Cognito. Interestingly, the app runs smoothly when tested locally using either next dev or next start. However, upon deploying it on the producti ...

Defined interface with specific number of members

I am tasked with creating an interface that has only two members, one of which is optional and both have undefined names. Something like: interface MyInterface { [required: string]: string|number [optional: string]?: string|number } Unfortunately, ...

The date selected in the date picker does not display in the view until the calendar is opened

I am currently working with two date pickers named startDate and endDate. My goal is to set up a basic date validation system where the start date cannot come after the end date. The main requirement is that if the user selects an end date that is earlier ...

TS7053: The element is implicitly assigned an 'any' type as the expression of type 'string' cannot be used to index the type '{ username: string; email: string; '

Having trouble incorporating TypeScript into a custom React Form Component, and I keep encountering an error that I can't seem to resolve. Error message TS7053: Element implicitly has an 'any' type because expression of type 'string&apo ...

Troubleshooting Cross Origin Error in C# and Angular

We are currently in the process of developing a website using Angular 5. The backend has been created utilizing .Net Web API and SQL Server. Our plan is to deploy the website on Azure, making it accessible both from the internet and the intranet. After co ...

Uploading Multipart Files and JSON Data using Spring Boot

I am looking to create an API using Spring Boot for uploading a multipart file as part of the JSON body, and also to save the image URL in a database. The requests will have the following format: ------WebKitFormBoundarynBsAcX7rJhOGsmfY Content-Dispositio ...

Solving the 'never' type issue in Vue3 and TypeScript for an empty array reference

I am currently in the process of migrating a component from an old Vue project that relies solely on JavaScript to a TypeScript/Vue project, and I have encountered some obstacles along the way. <script lang="ts"> import { computed, ref } fr ...

Error: The variable "prisma" is not defined in this context - Next.js version 14

While working with Prisma and next.js 14, I encountered an issue with the Stripe payment API. The error message ReferenceError: prisma is not defined popped up. How can I resolve this? import { NextApiRequest, NextApiResponse } from "next" import ...

Error Message: "Unable to access property 'proposta_usuario' of undefined in Angular 2 Data Binding"

I've been encountering some issues while trying to bind data from an input in Angular 2. Below is the HTML code snippet: <input type="text" class="animated bounceIn input-proposta" placeholder="Enter your proposal" [(ngModel)]="propo ...

Tips for streamlining the use of http.get() with or without parameters

retrievePosts(userId?: string): Observable<any> { const params = userId ? new HttpParams().set('userId', userId.toString()) : null; return this.http.get(ApiUrl + ApiPath, { params }); } I am attempting to streamline the two http.get ca ...

What is the process for transforming a Typescript source file into JavaScript?

I have a basic HTML file with a script source set to index.ts. index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge ...

Union types can be used to constrain generic type parameters in Typescript

I'm working on a function uniqueIds(first: any[], second: any[]): number[] { let prop = first[0] instanceof Owner ? "OwnerId" : "BankId"; return _.unique( _.map( first, o => ...

Dependency mismatch in main package.json and sub package.json

Imagine you have a project structure in Typescript set up as follows: root/ api/ package.json web/ package.json ... package.json In the main package.json file located in the root directory, Typescript is installed as a dependency to make ...

Creating a tsconfig.json file that aligns perfectly with your package.json and tsc command: a step-by-step

I've chosen to use TodoMvc Typescript-Angular as the starting point for my AngularJS project. Everything is working smoothly so far. Here's a breakdown of what I can do: To manage all dependencies, I simply run npm install or npm update based o ...