Ben Racicot
Ben Racicot

Reputation: 5893

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

Upvotes: 0

Views: 6269

Answers (2)

alebianco
alebianco

Reputation: 2555

The error message seems clear, you're trying to set attributes on an object that doesn't exist.

if this.authService.user === null you cannot set it's properties.

You have first to create a new User(...) somewhere and assign it to this.authService.user then you can go and change it's properties as needed.

Upvotes: 1

Christopher Moore
Christopher Moore

Reputation: 3099

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

Upvotes: 1

Related Questions