Constructing objects in TypeScript is a breeze with its C#-ins

It seems like finding a simple solution for my task is proving to be quite challenging. I have a class that accepts 10 parameters, most of which are optional. To simplify things, I will illustrate my dilemma using just 3 parameters.

I wish to be able to instantiate the PageConfig Constructor without having to include all optional parameters. For example:

new PageConfig({getList: this.getList})
new PageConfig({getList: this.getList, canDelete: false });
new PageConfig({getList: this.getList, isSliding: true });

I attempted the following approach.

export class PageConfigArgs {
    canDelete?: boolean;
    isSliding?: boolean;
    getList: (pagingInfo: PagingInfo) => Observable<any>;
}

export class PageConfig extends PageConfigArgs {
  constructor({
    isSliding = false,
    canDelete = true
  }: PageConfigArgs) {}
}

Since getList is mandatory, it does not have a default value in the constructor.
However, the challenge lies in referencing getList from the constructor to assign it internally.

How can I create a new configuration class that combines optional and required parameters?

Edit My primary goal is to establish a straightforward initialization process that eliminates the need to configure the class further post-instantiation.

Edit Marked as duplicate, I was unaware that I needed to declare all desired properties within the config class. Refer to previous question for resolution

Answer №1

I'm having trouble figuring out how to reference getList within the constructor so that I can assign it to the internal property.

It seems like you're referring to the member of the class when you mention the "internal one."

One way to tackle this issue is by using destructuring in the constructor's body.

Once destructured, you can then assign the object property to a member of the class.

export class PageConfigArgs {
    canDelete?: boolean;
    isSliding?: boolean;
    getList: (pagingInfo: PagingInfo) => Observable<any>;
}

export class PageConfig extends PageConfigArgs {
  private getList: (pagingInfo: PagingInfo) => Observable<any>;

  constructor(args: PageConfigArgs) {
    const { isSliding = false, canDelete = true } = args;
    this.getList = args.getList;
  }
}

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

Upon upgrading @types/angular, I encountered error TS2694 stating that the namespace 'angular' does not have an exported member 'xxx'

Following the upgrade of angular and @types/angular to version 1.6.x, an array of TS2694 errors suddenly appeared: error TS2694: Namespace 'angular' does not include an exported member named 'material' error TS2694: Namespace 'ang ...

Learn how to transform an object into an array consisting of multiple objects in TypeScript

The car's details are stored as: var car = {model: 'Rav4', Brand: 'Tayota'} I need to convert this information to an array format like [{model: 'Rav4', Brand: 'Tayota'}] ...

Defining Objects in TypeScript

Within my TypeScript application, I currently have the following code: interface Data { url: string, // more stuff } (...) export class something() { public data: Data; } method(){ this.data.url = "things"; } However, every time I atte ...

Encountering the "Maximum Update Depth Exceeded" error in React Typescript with hooks

I encountered this error: Uncaught Error: Maximum update depth exceeded. It seems to be related to calling setState multiple times within componentWillUpdate or componentDidUpdate. React limits nested updates to prevent infinite loops. I am unsure of what ...

Guide on effectively converting a table of tuples to an array of objects utility function (similar to zip) while preventing the merging of all values in typescript version 5.2.2

Almost there, but stuck on the final TS2322: Type TcolTuple[i] is not assignable to type string | number | symbol compiler error. Here's a nifty utility function called rowsToObjects() that many developers have probably come up with at some point, ...

Ways to link information from one entity to another

Currently, I am utilizing the TMDB API to showcase movies along with their respective genres. In my code, I have two objects where I retrieve details for movies and genres as shown below: listTrendingMovies() { this.listMediaService.listTrendingMovie ...

Tips for effectively packaging the React 17 library alongside the latest JSX transformation feature as an ES Module

I am currently in the process of creating a basic library consisting of React components that I intend to publish as an ES Module package for NPM. With the utilization of React 17, I have incorporated the new JSX transform into my code. To generate the ES ...

React slick slider not functioning properly with custom arrows

"I have encountered an issue while trying to implement multiple sliders in my component with custom arrows positioned below each carousel. Despite following the documentation meticulously, the arrows do not respond when clicked. What could possibly be ...

Encountering an Issue: The formGroup function requires an instance of a FormGroup. Kindly provide one

I am a beginner with Angular 2 and despite reviewing numerous stack overflow answers, I still can't resolve my issue. I have recently started learning about angular reactive forms and wanted to try out my first example but I'm facing some diffic ...

Is there a convenient method for setting up and activating real-time TypeScript checking in Windows 10 using VS Code?

After successfully installing VS Code on my Windows 10 system, I decided to follow the instructions provided here. Upon completion, Node and NPM were also installed correctly. However, I noticed a gap in the setup instructions between installing TypeScrip ...

Building an Angular 4 app featuring a customized default landing page and URL parameters functionality

I am in the process of developing a web portal that will be embedded within an iFrame. Below is the code snippet I am using to set up the portal: Routes Configuration const routes: Routes = [ { path: '', redirectTo: '/dash ...

Tips for effectively invoking an API within a Next.js application

I've been exploring the most effective method for calling an external API within a Next.js application recently. Given my experience in developing MERN stack applications, I typically rely on axios for handling API requests and utilize it within a use ...

Is the 'case' in a switch statement not treated as a typeguard by Typescript?

Here is a simplified version of the code I am working with: type Todo = { id: string; text: string; }; type Action = | { type: 'DELETE'; payload: string } | { type: 'CREATE'; payload: Todo } function reducer(state: Todo[], ...

Bringing Typescript functions into the current module's scope

Is it possible to import and reference a module (a collection of functions) in typescript without the need for the Module. prefix? For instance: import * as Operations from './Operations'; Can I access Operations.example() simply as example()? ...

Error message: Unable to instantiate cp in Angular 17 application while building with npm run in docker container

After creating a Dockerfile to containerize my application, I encountered an issue. When I set ng serve as the entrypoint in the Dockerfile, everything works fine. However, the problem arises when I try to execute npm run build. Below is the content of my ...

Angular is throwing error TS2322 stating that the type 'string' cannot be assigned to the type '"canvas" while working with ng-particles

My goal is to incorporate particles.js into the home screen component of my project. I have successfully installed "npm install ng-particles" and "npm install tsparticles." However, even after serving and restarting the application, I am unable to resolve ...

Challenges arise when employing reduce with data types in an object

I want to transform an object in a function so that all keys are converted from Camel case to Pascal case. My Declaration: export interface INodeMailerResponseLower { accepted: string[]; rejected: string[]; envelopeTime: number; messageTim ...

Access the data within a jsonArray using Cypress

I'm dealing with a test.json file that contains a jsonArray [{ "EMAIL": "email_1", "FIRST_NAME": "Daniel" }, [{ "EMAIL": "email_2", "FIRST_NAME": "John" }] ] I'm trying to figure out how to use cypre ...

Interactive form control for location details including country, state, district, and town

I am struggling with adding dynamic form controls on dropdown change. I have been able to add them, but encountered an error preventing me from retrieving the value in 'formName.value'. The specific error message states: "Error: There is no Form ...

Issues with Vercel's JavaScript Environment Variables Accessibility

I am encountering an issue trying to access environment variables on Vercel using JavaScript (TypeScript). Despite setting them under /settings/environment-variables, I receive undefined when attempting to access them with process.env.TURSO_DATABASE_URL du ...