簡體   English   中英

如何在超類構造函數中初始化/設置值? 在打字稿中

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

給定這兩個類:

用戶

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

    }

和從User 擴展的 UserEdit

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;

}

創建新對象后,可以從UserEdit中將email設置為空字符串”。 例如。

let userEdit:UserEdit = new UserEdit()

您需要使用super(param1, param2, param3, ...)在基類內部傳遞參數

在你的情況下

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

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

謝謝西蒙娜雷,我也找到了另一個優雅的功能組合解決方案。

像這樣。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM