Yoarthur
Yoarthur

Reputation: 917

How to init/set value in a superclass constructor? in Typescript

Given these two classes:

User

    export class User {

        constructor(id?: string, userName?: string, fullName?: string,
 email?: string, jobTitle?: string, phoneNumber?: string, roles?: string[]) {
            this.id = id;
            this.userName = userName;
            this.fullName = fullName;
            this.email = email;
            this.jobTitle = jobTitle;
            this.phoneNumber = phoneNumber;
            this.roles = roles;
        }

    }

and UserEdit that extends from User

import { User } from './user.model';


export class UserEdit extends User {
    constructor(currentPassword?: string, newPassword?: string, confirmPassword?: string) {
        super();

        this.currentPassword = currentPassword;
        this.newPassword = newPassword;
        this.confirmPassword = confirmPassword;
    }

    public currentPassword: string;
    public newPassword: string;
    public confirmPassword: string;

}

It's possible from UserEdit set an email to an empty string '', from the creation of the new object?. For example.

let userEdit:UserEdit = new UserEdit()

Upvotes: 0

Views: 1719

Answers (2)

Yoarthur
Yoarthur

Reputation: 917

Thanks Simonare, also i found another solution which is elegant aswell, function composition.

Like this.

public user: User = new User('', '', '', '', '', '', ['']);
public userEdit: editUser = new UserEdit('', '', '');
public edit = () => { ...this.user, ...this.userEdit };

Upvotes: 0

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30655

you need to pass parameters inside your base class by using super(param1, param2, param3, ...)

in your case

super(id, userName, fullName, email, jobTitle, phoneNumber, roles);

super(id, username, fullname, '', jobTitle, phoneNumber, roles);

Upvotes: 2

Related Questions