Obtain access to the interface from the base class

I am looking for a way to define an interface in a child class that can be accessed by a method in the parent abstract class.

For instance, consider the following code snippet:

export default abstract class MyClass {
    protected foo(arg: this.myInterface): any {
        //
    }
}

export default class FooClass extends MyClass {
    protected myInterface: DataInterface;
}

In this example, the DataInterface interface should be accessible through the foo method in the MyClass abstract class. Is this achievable? If not, what would be the alternative approach?

-- EDIT

Just to provide some context, the Abstract Class I am working with is named BaseService, and I am planning on creating services that inherit from it.

These services will utilize multiple interfaces, and it is crucial for me to be able to access these interfaces from the BaseService to ensure the correct data structure is being used.

The data structures I need to validate are related to attributes for a table in a SQL Server database, which means they could vary widely.

For example:

export interface IVehicleData {
    vehicle_id?: number;
    vehicle_name?: string;
    vehicle_created_at?: Date;
    vehicle_updated_at?: Date;
  }

In different classes, I might have different interfaces with unique attributes. Additionally, there could be several interfaces utilized, not restricted to just one.

Answer №1

Your explanation is somewhat unclear as the property myInterface in FooClass will represent an object that satisfies the interface, not the interface itself.

Nevertheless, this design pattern is acceptable. The abstract class must acknowledge the presence of a myInterface property. Presumably, there exists a common base interface to facilitate performing similar actions across multiple interfaces with different implementations?

You can make use of generic classes to ensure each class is aware of its specific interface type. By requiring all classes to extend a shared base, the abstract class can handle functions dependent on the base type while allowing child classes to implement behavior unique to their interface.

Note: I have revamped the code so it no longer relies on a shared BaseInterface. Instead, the base class mandates that its children implement certain methods or possess specific properties, thereby enhancing the utility of the base class.


abstract class MyClass<T> {
    protected rawData: T;

    constructor(myInterface: T) {
        this.rawData = myInterface;
    }

    protected foo(arg: T): any {
        //
    }

    abstract getId(): number;

    protected doSomethingWithId(): any {
        // the base class can utilize the id without needing to know how getId is implemented
        const id = this.getId();
    }
}

class VehicleClass extends MyClass<IVehicleData> {

    public okMethod(arg: IVehicleData) {
        this.foo(arg);
    }

    public badMethod(arg: {}) {
        this.foo(arg);  // throws an error since this.foo only accepts the current class's type
    }

    public getId(): number {
        // methods can be specifically implemented based on the data type being used
        return this.rawData.vehicle_id || -1;
    }
}

New Playground Link

Old Playground Link

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

An issue has occurred: The module named 'ApprovalModule' must be compiled using the JIT compiler, however, the necessary compiler '@angular/compiler' is not currently accessible

Issue: Error: The NgModule 'ApprovalModule' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available. JIT compilation is not recommended for production environments. Consider using AOT mode instead. Alterna ...

Tips for retrieving input values when they are not available in HTML documents

In this code snippet, I am creating an input element with the file type without adding it to the DOM. My goal is to retrieve the value of this input once the user selects a file. Even though the input is not part of the HTML template, I still want to acces ...

Classifying Union Types based on their distinct characteristics

There is a specific type with its own unique property (method) type Functions = { method: "connect", request: number, response: number, } | { method: "remove", request: string, response: string, } I aim to create a function that can handle inp ...

Manage both the return of an observable and the setting of a value within a single method using

I am in need of a service that can both return an observable and set a value to a field within the same method. The current implementation of my userService.getUserDetails() method is as follows: private requestUrl: string; private bic: string; private i ...

Is there a way to verify if the object's ID within an array matches?

I am looking to compare the ID of an object with all IDs of the objects in an array. There is a button that allows me to add a dish to the orders array. If the dish does not already exist in the array, it gets added. However, if the dish already exists, I ...

What is the best way to implement a Promise Function within a For loop?

Here is a function called sendEmail: public async sendEmail (log: LogMessage): Promise<void> { nodemailer.createTestAccount(async () => { return ServiceFactory.getSystemService().getNetworkPreferences().then(async (networkPreferences) => ...

Unleash the power of zod by seamlessly accessing both parameters and queries

In the zod-middleware documentation, an example is provided: export async function endpointCode(req: TypedRequestBody<typeof bodySchema>, res: Response) { const typedBody = req.body; return res.json(typedBody); } This example demonstrates access ...

Tips for sending arguments to translations

I am currently implementing vuejs 3 using TS. I have set up my translation files in TypeScript as shown below: index.ts: export default { 'example': 'example', } To use the translations, I simply do: {{ $t('example') }} N ...

Swap out the traditional for loop with a LINQ query utilizing the any method

In my TypeScript code, I have the following snippet: public executeTest(test: Test): void { const testFilters: Record<string> = getTestFilters(); let isTestingRequired: boolean = false; for (let i: number = 0; i < testFilters.leng ...

The expansion feature of PrimeNG Turbotable

I'm currently facing an issue with the Primeng Turbotable where I am unable to expand all rows by default. You can find a code example of my problem at this link. I have already tried implementing the solution provided in this example, but unfortuna ...

Encountering a "ReferenceError: global is not defined" in Angular 8 while attempting to establish a connection between my client application and Ethereum blockchain

I'm trying to configure my web3 provider using an injection token called web3.ts. The token is imported in the app.component.ts file and utilized within the async ngOnInit() method. I've attempted various solutions such as: Medium Tutorial ...

Encountering the error "Unable to access the 'user' property of an undefined object when working with Angular and Firebase

Exploring Firebase for the first time while attempting to configure email and Google authentication in an Angular (v5) application. While following a tutorial (), I encounter an error: ERROR TypeError: Cannot read property 'user' of undefined T ...

Guide to easily printing a page in Angular 4 using TypeScript

When using my web app, there are certain pages where I need to print only a specific component without including the sidebar. I have written the following TypeScript code to achieve this: print() { window.print(); } The relevant HTML code begins with: & ...

Backdrop styling for Material-UI dialogs/modals

Is there a way to customize the semi-transparent overlay of a material-ui dialog or modal? I am currently using material-ui with React and Typescript. https://i.stack.imgur.com/ODQvN.png Instead of a dark transparent overlay, I would like it to be transp ...

Utilize Angular 9 to fetch data from an API using the Get method, map them to a class, and

Seeking to extract information from a test URL and convert the data into a list, I aim to exhibit them in an alert/Loop for testing purposes. The dummy API URL being used is: The returned data follows this structure: {"status":"success","data":[{"id":"1" ...

Function parameter constrained to a specific property of a generic type T

In my codebase, I have a custom function called uniqBy, which filters out duplicate items based on a specified key: export function uniqBy<T>(array: T[], key: any): T[] { const seen = {}; return array.filter(function (item) { if (item ...

What steps can I take to have TypeScript limit the type of an array based on filter inference?

Here's a handy function that always returns an array of strings: (arr: (string | undefined)[]): string[] => arr.filter(item => item !== undefined); Check it out here However, TypeScript may not compile this code as expected due to its inferenc ...

How to resolve useState problem in useEffect when state is not null

Encountering issues with maintaining state in TypeScript React. A Child component passes a 'terminal' object to the Parent via a function called returnTerminal(). This 'terminal' object is then stored as a useState variable named _obje ...

The issue of broken reactivity arises when utilizing defineStore in Pinia with options instead of storeSetup

In my current project, I've implemented two different types of Pinia storage definitions. Here's a condensed look at each: // First Storage Definition using storeSetup export const useStore = defineStore("storeId", () => { const isExpanded: ...

Angular 14: Enhance Your User Experience with Dynamic Angular Material Table Row Management

My inquiry: I have encountered an issue with the Angular material table. After installing and setting up my first table, I created a function to delete the last row. However, the table is not refreshing as expected. It only updates when I make a site chang ...