Typescript: Establishing a class method with parameters that are inherent to the class

After creating a class, I realized that there is repeated logic that can be extracted into a method on the class to be reused by other properties of the class.

class Card {
  protected readonly data: Data;
  protected readonly user: User;
  nameVal: string;
  addressVal: string[];

  constructor(raw_data: Data, user: User) {
    this.data = raw_data;
    this.user = user;
  }

  get name(): string {
    if (!this.nameVal) {
      this.nameVal = name_getter(this.data, this.user); // same parameters
    }
    return this.nameVal;
  }

  get address(): string[] {
    if (!this.addressVal) {
      this.addressVal = address_getter(this.data, this.user); // same parameters
    }
    return this.addressVal;
  }

  // The goal is to refactor the above logic and centralize it in a function like below
  // maybe getter type would be something like this: 
  // type FieldValueGetter = (data: Data, user: User) => any;
  getFieldValue(getter: FieldValueGetter, field: ?) { // Is there a way to define field type? 
    if(!field) {
      this.field = getter(this.data, this.user);
    }
    return this.field;
  }
}

Questions arise regarding defining the type for the field parameter in the getFieldValue method, as the value of the field may differ based on the field. However, the common factor is that the field would be part of the class.

Answer №1

It seems like this is the information you are seeking.

keyof

function getter(data:Data, user:User, field: string){
// Insert your unique logic in this space.
}
class Card {
    protected readonly data: Data;
    protected readonly user: User;

    field: string = '';
    field2: number = 0;

    constructor(raw_data: Data, user: User) {
        this.data = raw_data;
        this.user = user;
    }

    getFieldValue<T>(getter: FieldValueGetter, field: keyof this): T {
        if (!field) {
            this[field] = getter(this.data, this.user, field);
        }
        return this[field] as any as  T;
    }
}

const card = new Card({}, {});
card.getFieldValue<string>(getter, 'field');
card.getFieldValue<number>(getter, 'field2');

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

Sending an array of data using Angular in a web service

Here is my model object from model.ts name_id: string[]; public generateUrlencodedParameters(token: string, id?: number): string { let urlSearchParams = new URLSearchParams(); urlSearchParams.append('name_id', this.name_id.toS ...

Error alert! A token error has been detected while executing Angular tests under <Jasmine>

I've been navigating the world of Angular testing, but I've hit a roadblock that I can't seem to bypass. Despite my efforts to consult the documentation and scour Google for answers, I remain stuck with a cryptic error message stating "Inval ...

There is an issue with types in React when using TypeScript: The type '(user: User) => Element' cannot be assigned to the type '((props: User) => any) & ReactNode'

I'm encountering an error in the terminal and need some assistance. I am not well-versed in TypeScript, so any guidance to resolve this issue would be highly appreciated. https://i.stack.imgur.com/PWATV.png The Loadable component code: import { Circ ...

How to select a DOM element in Angular 2.x

Although it may seem simple, there are not many examples of using Angular 2.0 yet. In one of my components, I have a situation where I need to add a class to the body tag. However, my application is bootstrapped deeper than the body element, so I am looki ...

Transmit information using the buttonRenderer feature in Ag-Grid for Angular applications

Struggling to transfer data between two unrelated components by clicking on a cell in ag-Grid and passing the data to a form component. I utilized the buttonRenderer function to extract row data from ag-Grid, but I'm unsure how to pass it to the secon ...

Convert JSON data into an array of strings that are related to each other

I'm encountering an issue with converting JSON into a string array I must convert a JSON into a string array to dynamically INSERT it into our database, as I need this to work for any type of JSON without prior knowledge of its structure. Here is th ...

Developing a specialized command-line application for currency conversion is my current project

Currently, I am working on developing a command-line application for currency exchange. I have created an interface to define the structure of an object array that will store the keys and values of currency names along with their current values in the inte ...

Guide on using automapper in typescript to map a complex object to a "Map" or "Record" interface

I have been utilizing the automapper-ts with typescript plugin for automatic mapping. Check it out here While it works smoothly for simple objects, I encountered issues when dealing with complex ones like: Record<string, any> or Map<string, Anoth ...

Angular testing with Jasmine and TypeScript

I've been attempting to create some Angular Controller tests for my App using TypeScript for a few days now, but haven't had any success. Let me start by saying that this is my first time writing tests in Jasmine. My issue is that I'm having ...

When buttons are clicked within Angular Material's Card component, it automatically triggers the click event of the card itself

One of the challenges I'm facing is having a mat-card within a component template: <mat-card *ngFor="let p of products" (click)="viewProduct(p)"> <mat-card-actions> <button mat-stroked-button (click)="addProductToCart(p)"&g ...

Encountering an issue in Angular where data.slice is not functioning properly, resorting to using parseInt to convert strings into Date

Looking to convert the data retrieved from the database into numbers and dates with ease. One set of data is in milliseconds while the other is in timestamps. https://i.stack.imgur.com/HdM0D.png The goal is to transform both types into numbers first, the ...

Develop an interface in TypeScript for intricate data structures

Displayed below is a variable that contains a collection of objects: scenes = { sky: { image: 'assets/1.jpg', points: { blue_area: { x: 1, y: 2 }, } }, blue_area: { image: & ...

saving the MediaObject to Ionic's storage with the set method

I attempted to save a Media Object on ionic storage, but encountered an error message stating: "error while saving media object in storage.set" https://i.sstatic.net/5jEaQ.jpg How can I successfully save a media object using storage.set and retrieve it ...

Passing a variable from an observable to another function in Angular2: A step-by-step guide

The code snippet below is not functioning as expected. I'm attempting to pass a variable obtained from an rxjs observable function to another function, but I'm uncertain of the correct method to do so and haven't been able to find a suitable ...

Troubleshooting Node TypeScript with Visual Studio Code using webpack bundling

(In a similar context to this query, but more focused on VsCode) I am attempting to debug the AngularU starter kit with Visual Studio Code. However, it is combining the TypeScript output into one bundle.js along with a side bundle.js.map: ↳web ↳dis ...

Error message while attempting to update devextreme-datagrid: "Received HTTP failure response for an unknown URL: 0 Unknown Error"

Need help with updating the devextreme-datagrid. Can anyone assist? lineController.js router.put("/:id", (req, res) => { if (!ObjectId.isValid(req.params.id)) return res.status(400).send(`No record with given id : ${req.params.id}`); ...

Typescript disregarding conditional statements

Looking for some assistance with a Next.JS React-Typescript application Here's my code snippet for handling the video HTML element const videoRef = useRef<HTMLVideoElement>(); useEffect(() => { videoRef !== undefined ? videoRef.current. ...

Encountering problem with npm ERR! peer @angular/common@"^12.0.0" while trying to install @ng-bootstrap/[email protected]

Encountering an issue during the deployment of my Angular application. I added the @ng-bootstrap/ng-bootstrap package, but there seems to be a dependency resolution problem causing the issue. 22-Dec-2022 07:03:47 npm ERR! Could not resolve dependency: 2 ...

What are the limitations of using concatMap for handling multiple requests simultaneously?

In my current function, I am receiving an array of objects called data/ids as a parameter. Within this function, I need to execute a post request for each element/id: fillProfile(users) { const requests = []; console.log( 'USERS.length:&apos ...

Is it possible to include a conditional type in TypeScript using inlining?

Apologies if this question seems basic to those well-versed in typesystems. I'm puzzled by the difference in outcomes when inlining a conditional statement in TypeScript. For instance, using the Extract conditional leads to different results dependin ...