打字稿如何使用可选链接
Typescript how to use optional chaining
为什么我在赋值时遇到错误;
state.user?.weight.budget = budget;
我试过几次这样的
(state.user?.weight.budget ?? 0) = budget;
那也不行。我做错了什么。我不明白
提前致谢。
可选链接尤其 not support assignment. The feature was discussed but they decided it was out of scope for the initial proposal and that it might be implemented "later". See this comment。
你的后一个例子 (state.user?.weight.budget ?? 0) = budget;
也不会工作,因为你不仅试图做一个可选的链接赋值,而且你还试图赋值给一个可能不是变量的表达式或变量的 属性 (0 = budget
?).
目前,在可能未定义 user
属性 的情况下进行赋值的唯一方法是通过没有可选链接的控制流,如下所示:
if (state.user != null) state.user.weight.budget = budget;
或一些等效的测试和可能分配代码。好的,希望有所帮助;祝你好运!
为什么我在赋值时遇到错误;
state.user?.weight.budget = budget;
我试过几次这样的
(state.user?.weight.budget ?? 0) = budget;
那也不行。我做错了什么。我不明白
提前致谢。
可选链接尤其 not support assignment. The feature was discussed but they decided it was out of scope for the initial proposal and that it might be implemented "later". See this comment。
你的后一个例子 (state.user?.weight.budget ?? 0) = budget;
也不会工作,因为你不仅试图做一个可选的链接赋值,而且你还试图赋值给一个可能不是变量的表达式或变量的 属性 (0 = budget
?).
目前,在可能未定义 user
属性 的情况下进行赋值的唯一方法是通过没有可选链接的控制流,如下所示:
if (state.user != null) state.user.weight.budget = budget;
或一些等效的测试和可能分配代码。好的,希望有所帮助;祝你好运!