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

Error during Next.js build: Incompatible types - cannot assign type to 'never'

Encountering an error in the console while attempting to build my project: .next/types/app/facebook/page.ts:8:13 Type error: Type 'OmitWithTag<typeof import("D:/projects/abkh24/client/app/facebook/page"), "metadata" | "defa ...

Creating non-changing identifiers with ever-changing values in Angular by leveraging TypeScript?

I need to transform all the labels in my application into label constants. Some parts of the HTML contain dynamic content, such as This label has '1' dynamic values, where the '1' can vary based on the component or a different applicat ...

Circular reference in Angular/TypeScript

I encountered a circular dependency issue in my Angular project and tried various solutions, including exporting all dependent classes from a "single file" as suggested here. Unfortunately, this approach did not work for me. I then explored other solutions ...

The error message ``TypeError [ERR_UNKNOWN_FILE_EXTENSION]:`` indicates a

I am encountering an error while trying to run the command ./bitgo-express --port 3080 --env test --bind localhost: (node:367854) ExperimentalWarning: The ESM module loader is experimental. internal/process/esm_loader.js:90 internalBinding('errors ...

Is it possible to release a typescript package without including the ts files in the

I have a Typescript project that needs to be published. All generated JS files are stored in a directory named build, and declaration files in another directory called declaration. I do not want the .ts files to be included in the published version. Can an ...

`What exactly do auth.guard.ts and the AuthenticationService do in Angular 8?`

import { Injectable } from '@angular/core'; import { AuthenticationService } from './_services'; import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; @Injectable({ providedIn: & ...

Creating intricate structures using TypeScript recursively

When working with Angular and TypeScript, we have the power of generics and Compile-goodness to ensure type-safety. However, when using services like HTTP-Service, we only receive parsed JSON instead of specific objects. Below are some generic methods that ...

Conceal the PayPal Button

Currently, I'm facing a challenge where I need to dynamically show or hide a PayPal button based on the status of my switch. The issue is that once the PayPal button is displayed, it remains visible even if the switch is toggled back to credit card pa ...

The revalidation process in react-hook-form doesn't seem to initiate

Stumbled upon a code example here Decided to fork a sandbox version (original had bugs and errors) I am trying to implement custom validation callbacks for each form input element by providing options in the register function, but the validate is only tr ...

I am experiencing an issue with mydaterangepicker and primeng where it is not displaying properly in the table header. Can anyone assist me with this

I am attempting to integrate mydaterangepicker () with primeng turbotable (since primeng calendar does not meet the requirements), but I am having trouble with its display. Could you please assist me with some CSS code or suggest an alternative solution? ...

Combining marker, circle, and polygon layers within an Angular 5 environment

I am working on a project where I have an array of places that are being displayed in both a table and a map. Each element in the table is represented by a marker, and either a circle or polygon. When an element is selected from the table, the marker icon ...

Component in Next.js fetching data from an external API

I am attempting to generate cards dynamically with content fetched from an API. Unfortunately, I have been unsuccessful in finding a method that works during website rendering. My goal is to pass the "packages" as properties to the component within the div ...

Angular 6 Calendar Template issues with parsing: Unable to link to 'view' as it is not recognized as a valid property of 'div'

I am in the process of developing an application that utilizes this angular calendar. My tech stack includes Angular 6 with AngularFire2 and Firebase. Below is my app.module.ts file: import { BrowserModule } from '@angular/platform-browser'; imp ...

Navigating SSL certificate prompts in Protractor

Our programs utilize SSL certificates and we are unable to bypass Chrome's prompt for selecting a certificate. We would be satisfied with simply choosing the one certificate needed. Attempts have been made using this code: capabilities: { browser ...

When attempting to send a token from an account to a marketplace in ERC721, the transfer caller must either be the owner

Currently, I am in the process of transferring my NFT to a marketplace pragma solidity ^0.8.7; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import & ...

Issue with saving date values accurately in Nestjs/Prisma

After logging the response body before saving it to the database, I noticed that the shape is correct. Here's what it looks like: //console.log response body CreateOpenHourDto { day: 'WEDNESDAY', startTime: 1663858800000, endTime: 16638786 ...

Tips for finalizing a subscriber after a for loop finishes?

When you send a GET request to , you will receive the repositories owned by the user benawad. However, GitHub limits the number of repositories returned to 30. The user benawad currently has 246 repositories as of today (14/08/2021). In order to workarou ...

Transform Observable RxJS into practical results

In a straightforward scenario, I have an upload action on the page that looks like this: onUpload$: Subject<SomeUpload> = new Subject<SomeUpload>(); uploadAction$: Observable<Action> = this.onUpload$.map(entity => this.someActionServi ...

The incredible power of the MongoDB $inc field

I am facing a challenge in writing a function that accepts a record id, an action (inc or dec), and a field name as a string to be incremented (can be 'likes', 'subs' or any other). The issue is that I am unable to find a way to replac ...

Experiencing a problem with updating records in angular?

angular version: Angular CLI: 9.0.0-rc.7 I have encountered an issue while trying to update a record. After clicking on the edit icon, I am able to make changes to the record in the form. However, when I click on the Edit Button, the record gets updated i ...