Search code examples
typescriptgetter-setter

Typescript: Autopopulate a property via getter/setter


I have a class for User Properties. I'm trying to auto-populate the 'fullname' property if firstName and lastName is updated. But so far, my code only populate it when it is updated manually by in the controller.

Is there a way to auto-update the 'fullname' without explicitly calling it?

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 : '');
    } }

Usage in controller:

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

Solution

  • You're going about this all wrong. You don't need to set fullName.. and you certainly don't need a local variable for it.

    export class UserDTO {
        id: number;
        firstName: string;
        lastName: string;
    
        get fullname(): string {
            return this.firstName + (this.lastName ? ' ' + this.lastName : '');
        }
    }
    

    When requesting fullname, it will always be up to date - and you cannot set it. You update it by setting firstName or lastName.