Methods for populating an object with Interface type and returning it

This is my function that populates an object based on interface type:

public _fillAddModel<T>(lessonId: number, studyPeriodId: number, confirmed: boolean = false): T {
    let data: T;
    data = {
      lesson: this.substitution.lessonNumber,
      schoolStudyPeriod: GlobalModel.getSelectedPeriod().id,
      confirmed: true
    };

    return data;
  }

You can call it like this:

let data = this._fillAddModel<ISubstitutionModelTeacher>(1, 2, true);
let data = this._fillAddModel<ISubstitutionModelAddTeacherSubject>(1, 2, true);

In this function, I populate the object using the T interface and then continue to fill additional fields after that:

data.subsDate = this.substitution.date;

All interfaces extend a main interface called ISubstitutionModelAdd:

export interface ISubstitutionModelTeacher extends ISubstitutionModelAdd {
  newTeacher: number;
  subsDate: string;
}

export interface ISubstitutionModelAddTeacherSubject extends ISubstitutionModelAdd {
  newTeacher: number;
  subsDate: string;
  classSubject: number;
}

export interface ISubstitutionModelAddFree extends ISubstitutionModelAdd {
  subsDate: string;
  remark: string;
}

The challenge is to initially populate the object with the default ISubstitutionModelAdd interface and then add additional data based on interface T.

Answer №1

If you need to initialize multiple properties in a TypeScript class, you can use an additional parameter that captures all the properties from a generic type T except for the ones specified as arguments:

class PropertyInitializer {
    _initializeProperties<T extends ICustomModel>(id: number, name: string, otherFields: Pick<T, Exclude<keyof T, 'id' | 'name'>>): T {
        let data = Object.assign({
            id: id,
            name: name
        }, otherFields);

        return data as any;
    }
    // Example
    test() {
        let data = this._initializeProperties<ICustomModelExample>(1, "example", {
            description: "description",
            value: 100
        });
    }

    // Helper methods
    getId(id: number): number{ return id; }
    getName(name: string): string { return name; }
}

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

Endpoint path for reverse matching in Mongodb API

I am currently in the process of setting up a webhook system that allows users to connect to any method on my express server by specifying a method and an endpoint to listen to (for example PUT /movies/*). This setup will then send the updated movie to the ...

Display sub-objects within Chart.js

I'm currently tackling a project in Ionic 3 where I am utilizing an API that returns a JSON response with nested objects. My goal is to display certain aspects of these objects within a bar graph using chart.js. Unfortunately, I lack experience in ma ...

When I delete the initial element from the array, the thumbnail image disappears

Using react-dropzone, I am attempting to implement image drag and drop functionality. The dropped image is stored in the React state within a files array. However, a problem arises when removing an image from the array causing the thumbnails of the remain ...

Check the @versionColumn value for validation prior to the entity save operation in TypeORM

I am currently in the process of saving data in a PostgreSQL database using TypeORM with NestJS integration. The data I am saving includes a version property, which is managed using TypeORM's @VersionColumn feature. This feature increments a number ea ...

"Encountering an error with the any type in the useLocation feature while using React Router version 6

https://i.sstatic.net/0YcS9.png What steps should I take to resolve this particular type of error issue? My attempt at passing a custom type did not yield successful results. ...

Ways to verify if an array contains elements from other arrays in Typescript

How can I verify if the winningConditions are present in chosenNumbers? The chosenNumbers array is of varying lengths and consists of a mix of numbers. For example, one of the winning conditions is [0, 3, 6], but there is also the number 2 included. How ...

Whenever I am building a React application, I encounter a bug that states: "node:fs:1380 const result = binding.mkdir()"

Whenever I try to enter the command: create-react-app my-app --template typescript I keep encountering this error message: node:fs:1380 const result = binding.mkdir( ^ Error: EPERM: operation not permitted, mkdir 'D:\ ...

The user interface is not being refreshed in the select box after removing control from the reactive form

Within my project, I am utilizing "@angular/cli": "1.2.6", "@angular/core": "^4.0.0" Objective My goal is to create a dynamic form for a product that includes feature inputs. When the user clicks the "add feature" button, a new feature column with a sel ...

Tips for sending data to CSS in Angular

I have an Angular application where I need to calculate the width of an element and store it in a variable called finalposition. Then, I want to move this element to the left by (finalposition)px when hovering over it. How can I achieve this styling effect ...

Having trouble with react-responsive-carousel in Next.js version 13?

I have been following a tutorial to create an eBay clone. One of the steps involves creating a carousel. However, when I add it, the carousel does not transition to the next page. I have attempted to uninstall and reinstall packages, but the issue persists ...

Issue encountered while implementing a recursive type within a function

I've created a type that recursively extracts indices from nested objects and organizes them into a flat, strongly-typed tuple as shown below: type NestedRecord = Record<string, any> type RecursiveGetIndex< TRecord extends NestedRecord, ...

Is it possible to compile a .ts file at the root level without following the tsconfig.json configurations?

After dealing with the challenge of having both .ts and .js files coexisting in each folder for months, I have finally managed to get the app to compile correctly. The transition from JS to TS brought about this inconvenience, but the overall benefits make ...

How to efficiently store and manage a many-to-many relationship in PostgreSQL with TypeORM

I have a products entity defined as follows: @Entity('products') export class productsEntity extends BaseEntity{ @PrimaryGeneratedColumn() id: number; //..columns @ManyToMany( type => Categories, categoryEntity => cat ...

Show refined information upon form submission or click

I am facing a challenge with implementing filtering functionality in an input box within a form in Angular 12. Despite my efforts, I have been unable to get the pipe working correctly in the component and consequently in the view. HTML ...

What steps should I take to transition from using require statements to imports with typescript in my mocha tests?

I have the following values in my package.json file: "scripts": { "test": "mocha -r ts-node/register security.test.ts" }, "type": "module", . . ...

Get rid of the strange border on the material dialog

I am struggling with the Angular material 6 dialog component as it is displaying a strange border. I have attempted to remove it using the code below, without success. Interestingly, when I apply the style inline in the browser, it works fine. Any suggesti ...

Encounter the "Error: Source 'cloudsTileLayer-RasterSource' not found" message while trying to integrate a weather tile layer into Azure Maps

I have been working on a React application that utilizes the React-Azure-Maps npm package. My current challenge involves creating a weather layer, which I believe shares similarities with the sample code provided for layers. The code snippet responsible f ...

react-data-table-component establishes the structure of the expanded element

Has anyone encountered an issue with the react-data-table-component? I need to pass a row type (typescript model) to the Detail component that is rendered when the row is expanded. Detail: export const Detail = (row: certificates) => { //it works fine ...

When utilizing a personalized Typescript Declaration File, encountering the error message 'Unable to resolve symbol (...)'

I'm having trouble creating a custom TypeScript declaration file for my JavaScript library. Here is a simplified version of the code: App.ts: /// <reference path="types.d.ts" /> MyMethods.doSomething() // error: Cannot resolve symbol "MyMetho ...

Experimenting with nested dual dynamic routing within the app's directory

Currently working with NextJS 13 and executing the following operations within the app directory. I am attempting to utilize the generateStaticParams function to generate static pages during build time. The route structure is: subpage/[categoryName]/[gif ...