初始化对象当tyscript中使用的strictnullchecks
我有一个称为iuser
的接口,并在打字稿设置中使用strictnullchecks
。我想在类似的类中使用iuser
的变量:
class UserAccount {
user: IUser;
}
上面的代码将生成错误:
属性'用户'没有初始化器,并且在构造函数中不确定。
我可以使用以下方式解决此问题:
class UserAccount {
user: IUser;
constructor() {
user = new User();
}
}
但是从运行时间角度来看,用户
只能在显示后一段时间后设置。从服务器获取用户
的数据有延迟。 用户
的设置是通过rxjs
可观察到的仅作用的。
我可以为user
进行哪种类型的初始化,以便仅在以后设置它。设置用户
to null
或undefined
可能不正确,因为我使用strictnullchecks
并表明该对象将会从一开始就存在。但是,在服务器调用完成之前,用户
的有效对象不存在。
***更新****
这比上面的示例要好得多:
export class AddPersonDialogComponent {
selectedPerson1: IPersonForTypeahead;
selectedPerson2: IPersonForTypeahead;
selectedPerson3: IPersonForTypeahead;
...
}
当用户从对话框中的三个3个下拉列表中选择它们时,分配了3 SelectedPerson
对象。这三个属性一无所有,但如果用户从对话框中的下拉列中选择人员,则将设置它们。
I have an interface called IUser
and uses strictNullChecks
in the typescript setting. I want to use a variable of IUser
in the class like below:
class UserAccount {
user: IUser;
}
The above code will generate the error:
Property 'user' has no initializer and is not definitely assigned in the constructor.
I can fix this with:
class UserAccount {
user: IUser;
constructor() {
user = new User();
}
}
But from a run time perspective, the user
can be set only after a while after the display is complete. There is a latency for getting the data for the user
from the server. The setting of the user
is done through an RxJS
observable which works only reactively.
What type of initialization I can do for user
so that it can be set only later time. Setting user
to null
or undefined
may not be correct because I use strictNullChecks
and showing the intention that the object will be present from the beginning. But a valid object for user
can't exist until the server call is complete.
*** UPDATE ****
This is a little more better example than the above:
export class AddPersonDialogComponent {
selectedPerson1: IPersonForTypeahead;
selectedPerson2: IPersonForTypeahead;
selectedPerson3: IPersonForTypeahead;
...
}
The 3 selectedPerson
objects are assigned values when the user select them from three 3 dropdowns in the dialog. These three properties start with nothing but if the user select people from a drop down in the dialog, they are set.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将
用户量的使用量
成为可观察的,这样:此处的想法是不要构造您的
userAccount
,直到您拥有所有需要的数据。这与您的想法“ ”一致,但是在服务器调用完成之前,不能存在一个有效的用户对象”。You could make your usage of
UserAccount
to be an observable, like this:The idea here is to not construct your
UserAccount
until you have all the data needed to do so. This goes along with your idea "But a valid object for user can't exist until the server call is complete" .