Using TypeScript to expand a class by introducing a constructor with Partial<Type>

How can the User class be extended in TypeScript using Partial<User> as the constructor?

I am open to alternative solutions that do not involve Partial. For instance, initializing a blank class with new User({})

Currently, the AdvancedUser class only inherits properties from the User class, without any additional advanced?: properties.

export class User {
    first_name: string = ''
    last_name: string = ''
    email: string = ''

    constructor(data: Partial<User>) {
        Object.assign(this, data)
    }
}

export class AdvancedUser extends User {
    advanced?: {
        foo?: string
    }

    constructor(data: Partial<User>) {
        super(data)
    }
}

The code provided is functional. An error in my project caused the AdvancedUser() call to revert back to User().

Answer №1

I am exploring alternative solutions that do not rely on Partial. For example, I am simply using the utility type to initialize a new class with empty values. For instance, creating a new User({})

Rather than the use of constructors with Partial, achieving the desired outcome can be done by leveraging the as keyword, which provides a cleaner approach in my view.

Regarding the advanced property, its absence from the output is due to the fact that it has not been initialized anywhere (neither inline nor in the constructor). If you intend to maintain it as an optional property, a simple initialization with undefined will suffice:

export class User {
    first_name: string = '';
    last_name: string = '';
    email: string = '';

    constructor(data: User) {
        Object.assign(this, data);
    }
}

export class AdvancedUser extends User {
    advanced?: {
        foo?: string
    } = undefined;

    constructor(data: User) {
        super(data);
    }
}

const au = new AdvancedUser({} as User);
/* OUTPUT:
AdvancedUser: {
  "first_name": "",
  "last_name": "",
  "email": "",
  "advanced": undefined
} 
*/
console.log(au);

Answer №2

Consider using Partial in this scenario:

interface IUserData {
  first_name: string;
  last_name: string;
  email: string;
}

interface IAdvancedUserData {
  doAdvancedStuff(IAdvancedStuffOptions) : string;
}

class AdvancedUserData implements IUserData, IAdvancedUserData {
  
}

To utilize Partial, ensure that your User accepts data of type Partial and then provide an AdvancedUserData instance to your AdvancedUser constructor.

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

What is the best way to iterate over JSON data and organize the output based on the key value?

Let's say I want to filter through the JSON data below and only push the home_team_conference if it matches Southeastern. My goal is to organize the data by home_team_conference in order to display each array on different pages of my website. Currentl ...

The jQuery script is functioning flawlessly in one specific direction

Currently, I am utilizing a basic script to alter the color of elements based on the div being hovered over. While this works smoothly in one direction down the line, when trying to reverse order and backtrack, the colors do not function as intended. The ...

How to retrieve the value of an element within a facebox div with jquery

On my page, I have two div tags displayed below. Whenever I try to retrieve the value of the itemName element using $('#itemName').val();, it always returns the value of the element in the first div (which is blank). Is there a way to access the ...

Tips for Saving process.argv in a .js File for Future Reference

I am struggling with passing process.argv value to a config file for later use. I am trying to call it from npm scripts. I have the following config file: module.exports = { foo: proccess.argv[2] } So far, I have tried calling it via node config.js &apo ...

Dollar Sign vs "$$()" Sparkling Protractor with "by.css()" vs "$()"

I'm a bit confused about the purposes of the $ and $$ commands. I initially thought they were just substitutes for 'by.css', but why use $$? <element id = "eId"></element> Based on the example above, I assumed that these two l ...

Transmit parameters via onclick event on FullCalendar

I have been utilizing the full calendar feature and it's been functioning properly. However, I am encountering an issue with sending parameters via onclick event. Below is the JavaScript code that I currently have: <script> $(document).ready(fu ...

Error encountered with MobileFirst version 8 and Angular JS v1.5.3 integration using Bootstrap

I am encountering an issue with my Cordova application that integrates with MobileFirst Platform version 8, Ionic version 1.3.1, and AngularJS version 1.5.3. Upon bootstrapping AngularJS to connect the app to MobileFirst Platform, I encounter the following ...

The confusing case of jQuery's e.preventDefault: Unable to submit form despite preventing default behavior

Objective: Prevent the 'submit' button from functioning, validate fields, generate popover alerts for results, and submit form upon closing of popover. To achieve this, I have set up a hidden popover div. When the submit button is clicked, I uti ...

What is the best approach to implement server-side rendering in Next.js while utilizing Apollo React hooks for fetching data from the backend?

I have a Next.js project that is utilizing Apollo GraphQL to retrieve data from the backend. My goal is to render the page using server-side rendering. However, I am encountering an obstacle as the React hooks provided by GraphQL Apollo prevent me from cal ...

Safari Browser does not currently offer support for MediaRecorder functionality

[Log] Webcam permission error Error: MediaRecorder is not supported I am facing an issue while trying to record audio. The Chrome browser allows audio recording without any problem, but Safari is throwing an error. global.audioStream = await navigator.m ...

Creating a personalized state object containing unresolved promises in React Native utilizing axios inside a custom React Hook

I'm currently in the process of creating a custom state within a custom Hook for React Native (non-Expo environment). The state I am working on looks like this: interface ResponseState { api1: { error: boolean; errorMsg?: string; ...

The JavaScript button's onClick event is not functioning properly, despite the method executing normally

I'm currently working on creating a button using JavaScript that, when clicked, will trigger an AJAX request to some PHP code. Interestingly, I have already set up three buttons with the same functionality and they are all functioning perfectly. Wha ...

Node.js and Express: tackling the problem of duplicate variables

I have a checkUser middleware that saves the user information when a JWT is verified. However, when I integrate it into my routes and attempt to log res.locals.user.username, the username appears twice in the console. This duplication is causing issues wit ...

Step-by-step guide on deleting an entire row from a PHP webpage

I have removed a row from the database, but now I need to also remove it from the interface on my PHP page. Any suggestions or assistance would be greatly appreciated. Here is a snippet of mypage.php: <tr> <td><?php echo $row[' ...

Developers specializing in Google Maps navigate to a particular destination

I have been working on an app that provides users with the best options for places to visit, utilizing Google Maps technology. Here is what I have accomplished so far: Show the user their current location Show the user possible destinations (with marker ...

What is the best way to display two cards while concealing a third one using a "show more"

Is there a way to hide certain cards by default and only show them when the user clicks on a "View more" button? I have multiple cards, but I want to hide the last one initially and reveal it when the button is clicked. I would really appreciate any assis ...

Learn how to automatically set the checked state of a radio button by toggling another radio button

I have two sets of radio buttons, each with four options. The first set has no default selection (unchecked) using jQuery, while the second set has the first option checked by default. What I'm looking to achieve is that when a radio button in the f ...

Efficiently finding a group of substrings within a JavaScript string

I am currently working on a method to efficiently search for specific substrings within a given string. Here is my current implementation: const apple = "apple" const banana = "banana" const chickoo = "chickoo" const dates = & ...

Limiting the number of checkboxes selected in a Checkbox Group based on

I am working on a checkboxGroupInput that has 4 options (denoted as A, B, C, D). My goal is to restrict the selection to only 2 choices. The user should be able to pick a 3rd option. In this scenario, only the newly selected (3rd) and previously selec ...

Tips on leveraging an attribute for type guarding in a TypeScript class with generics

Is there a way to utilize a generic class to determine the type of a conditional type? Here is a basic example and link to TS playground. How can I access this.b and this.a without relying on as or any manual adjustments? type X<T> = T extends true ...