打字稿:通过getter / setter自动填充属性

时间:2017-11-10 04:57:15

标签: typescript getter-setter

我有一个用户属性类。我试图自动填充全名'如果firstName和lastName已更新,则为property。但到目前为止,我的代码仅在控制器中手动更新时填充它。

有没有办法自动更新'全名'没有明确地称它?

export class UserDTO {
    id: number;
    fullname: string;
    firstName: string;
    lastName: string;

    private _fullname string;
    get fullname(): string {
        return this._fullname;
    }

    set fullname(value: string) {
        this._fullname = this.firstName + (this.lastName ? ' ' + this.lastName : '');
    } }

控制器中的用法:

updatedUser.name = firstName + (lastName ? ' ' + lastName : '');

1 个答案:

答案 0 :(得分:0)

你说这一切都错了。您不需要设置fullName ..并且您当然不需要本地变量。

export class UserDTO {
    id: number;
    firstName: string;
    lastName: string;

    get fullname(): string {
        return this.firstName + (this.lastName ? ' ' + this.lastName : '');
    }
}

请求fullname时,它始终是最新的 - 您无法设置它。您可以通过设置firstNamelastName来更新它。

相关问题