Typescript: Extend class with Partial constructor

Using typescript, how do extend the User class using Partial<User> as the constructor?

I am also open to solutions which do not use Partial. In this case I am only using the utility type to initialize a blank class. i.e. new User({})

Currently, AdvancedUser only has User properties, but none of the 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 provide code actually works. My project was suffering from a downstream typo reverting my AdvancedUser() call back to User().

Answer

I am also open to solutions which do not use Partial. In this case I am only using the utility type to initialize a blank class. i.e. new User({})

Instead of having constructors that use Partial, you can get the result you want by using the as keyword, which in my opinion is much cleaner.

As for the advanced property, the reason it’s not showing up is because it isn’t initialized anywhere (neither inline or in the constructor). Assuming you want to keep it as an optional property, all you need to do is initialize it with undefined:

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);