Creating a new generic class in Angular 7 by extending an existing generic class

In TypeScript, I have defined the following interfaces and classes:

export interface PageInterface<T> {
    count: number;
    previous: string;
    next: string;
    results: T[];
}

export class Page<T> implements PageInterface<T> {}

----------------------------------------------------------

export interface AdapterInterface<T> {
    adapt(item: any): T;
}

My goal is to implement PageAdapter<Page<T>>.

The attempted implementation resulted in errors (Type 'Page' si not generic):

export class PageAdapter<Page> implements AdapterInterface<Page> {
    adapt(item: any): Page<T> {
        return new Page<T>(item['count'], item['previous'], item['next'], item['results']);
    }
}

Replacing Page with Page<T> in the first line did not work at all.

I am seeking guidance on how to properly implement this. Any help would be greatly appreciated.

Thank you,

Answer №1

Perhaps you are seeking something along these lines:

export class PageAdapter<T> implements AdapterInterface<Page<T>> {
    adapt(item: any): Page<T> {
        return new Page<T>(item['count'], item['previous'], item['next'], item['results']);
    }
}

For instance, a PageAdapter<string> could serve as an

AdapterInterface<Page<string>>
. If the generic type parameter must be of a similar type to Page, you can try defining it like this:

export class PageAdapter2<P extends Page<any>> implements AdapterInterface<P> {
    adapt(item: any): P {
        return new Page(item['count'], item['previous'], item['next'], item['results']) as P;
    }
}

In this case, a

PageAdapter<Page<string>>
can function as an
AdapterInterface<Page<string>>
. However, the typings in this version may not be as polished and could require type assertions for implementation.

I hope this information proves helpful. Best of luck!

Access the code on Playground

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

Mastering the Art of Utilizing Generic Typing to Access Objects

I am trying to find a way to access an object by class using generic typing. The issue I am encountering is that I am getting an error when trying to check if the locators contain an input field. type '{ form1: { item2: { checkbox: string; input: st ...

Refactor and rename with VSCode and TypeScript without having to manually open the files being affected

When working with a TypeScript application in Visual Studio Code, is there a way to rename a variable or function without the affected files automatically opening in the Editor area? I prefer my refactorings to be applied immediately and the affected file ...

What is causing this TypeScript error to be raised by this statement?

Can you explain why the following statement is throwing a type error? const x: Chat = { ...doc.data(), id: doc.id } The error message states: Type '{ id: string; }' is missing the following properties from type 'Chat': message, name, ...

I require clarity on this befuddling syntax that feels like descending into

I came across this example in the official documentation at https://angular.io/guide/form-validation#custom-validators return (control: AbstractControl): {[key: string]: any} => { const forbidden = nameRe.test(control.value); return forbidden ...

The input of type 'Observable<true | Promise<boolean>>' cannot be assigned to the output of type 'boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree>'

I'm currently using a Guard with a canActivate method: canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { return this.fi ...

"Having issues with the ngrx/store initialization; the store is not

My shop has the following reducers : export const centralStampState = { layoutState : layoutReducer, //this one is not initialized eventTabState : eventTabReducer, eventTimelineState: eventTimelineReducer, eventWorkflowState : eventWorkflowReducer ...

Create a unit test scenario to test a function that returns a promise in the shape of an array utilizing Jasmine and Karma

I am just starting to learn about unit test cases and I have a method called 'loadEsriModules' that is being called from the ngOnInIt() function. Here is a sample of the code: ngOnInit() { debugger this.loadEsriModules().then(() => { ...

Ran into an issue while executing ng build --prod: The JavaScript heap has run out of memory

After executing ng build --prod, I encounter the error below. What steps can I take to resolve this issue? FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory ...

Initiate a class change in jQuery from an A element on a separate webpage

I recently took over the maintenance of a website and discovered that the previous developer had created a simple jQuery script to show/hide list elements on a single webpage based on the .active class. However, I am facing an issue in triggering the scr ...

Tips for displaying dynamic HTML content in Angular

Is there a way to dynamically display HTML content within {{ name }}? let firstName = "Faisal"; let data1 = "<h1>{{firstName}}</h1>"; let lastName = "Khan"; let data2 = "<h1>{{lastName}}</h1>"; How can I achieve the desired outpu ...

What is the process of unloading pages in Angular 2?

In the process of developing an Angular 2 application consisting of approximately 200 pages, we have considered various loading strategies such as lazy loading, eager loading, and pre-loading. A question that arises is whether a page that has been lazily ...

Is it possible for the Observable call in Angular 4 to function similarly to jQuery's synchronous AJAX method?

As I have a business logic function that needs to use HttpGet and I must wait for the result before continuing, jQuery's ajax can handle this easily. But I am curious if Observables have a similar feature? I was hoping for the result to be: John An ...

What is the purpose of utilizing import and require() in Node.js programming?

Currently, I am analyzing the source code found at "Type definitions for Express 4.16" and stumbled upon this interesting line (#18): import serveStatic = require("serve-static"); I couldn't help but wonder why the above code is necessary or being u ...

ReplaySubject in Angular is failing to update the array when a new object is added

I am encountering an issue where, upon attempting to create a new page Object, it successfully sends the data to the backend but does not update the array. I have to refresh the page in order to view the entire array. Within the frontend, I am utilizing O ...

In the process of developing a custom Vue component library with the help of Rollup and VueJS 3

My goal is to develop a custom Vue component library using rollup and Vue.js. The process went smoothly with Vue2, but I encountered issues parsing CSS files with Vue3. To address this, I updated the dependencies in the package.json file. package.json { ...

Passing a service from a custom element to a child custom element in Angular involves utilizing the

I have created a demonstration showcasing the creation of 2 custom Angular elements (refer to app.module). Everything is working smoothly, but I encountered a problem: when I provide a service in the parent element (named BarComponent), it does not get rec ...

Navigating Through the Angular Migration Journey

As I was researching how to integrate ES2020 with Angular, I came across the following useful link: https://angular.io/guide/migration-update-module-and-target-compiler-options The document begins by stating "This migration adjusts the target and module s ...

Developing an angular application

I recently finished developing a sample project using Angular that consists of 2 components and also includes a backend built with Node.js. Now, I am looking to deploy the Angular project and modify the base href to /name/. Could someone kindly provide gu ...

C++ templated classes that are internal

Currently, I am working on a small exercise for my c++ class and have made some progress so far. Although it is not yet fully completed, I am currently struggling with the recurring issue of template of internal class. I have come across various solution ...

Angular Tutorial: Modifying the CSS transform property of HTML elements within a component directly

Currently, I'm in the process of developing an analog clock for a project using Angular. My challenge is figuring out how to dynamically update the sec/min/hour handlers on the clock based on the current time by manipulating the style.transform prope ...