gpt4 book ai didi

javascript - 如何使用 setter 和 getter 在 TypeScript 中正确设置对象属性?

转载 作者:行者123 更新时间:2023-12-01 04:01:58 24 4
gpt4 key购买 nike

如何在 TypeScript 中使用 setter 设置对象的每个属性?

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

constructor(...){}

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

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

然后在任何地方设置都会在以下情况下出错:

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

更多:

用户模型:

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

错误:无法设置未定义的属性“id”

最佳答案

您需要将整个 user 对象传递给 setter,但您需要访问用户的所有其他属性

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

或者,为每个属性设置单独的 setter

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

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

你会这么称呼

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

关于javascript - 如何使用 setter 和 getter 在 TypeScript 中正确设置对象属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42118414/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com