Search code examples
javascriptangulartypescriptsettergetter-setter

How to properly set object properties in TypeScript with setters and getters?


How do you set each property of an object with a setter in TypeScript?

export class AuthService {
    private _user:User; // User is my model

    constructor(...){}

    public get user()
    {
        return this._user;
    }

    public set user(value){
        this._user = value;
    }
...

Then setting anywhere gives errors when:

this.authService.user.id = data.userId;
this.authService.user.isLoggedIn = 'true';

MORE:

The user model:

export class User {
    constructor(
        public email: string,
        public pass: string, 
        public id?: string,
        public fname?: string,
        public lname?: string,
        public isLoggedIn?: string){}
}

The error: Cannot set property 'id' of undefined


Solution

  • You need to pass the whole user object to the setter, but you would need access to all other attributes of the user

    this.authService.user = {
        id: data.userId,
        isLoggedIn: true
    };
    

    Alternatively, have individual setters for each property

    public set id(value){
        this._user.id = value;
    }
    
    public set isLoggedIn(value){
        this._user.isLoggedIn = value;
    }
    

    Which you would call as thus

    this.authService.id = data.userId;
    this.authService.isLoggedIn = 'true';