Skip to main content

空值合并操作

空值合并操作

如果你想用 TypeScript 来实现相同的逻辑,可以使用可选链操作符(optional chaining operator)和空值合并操作符(nullish coalescing operator),从而使代码更简洁。以下是用 TypeScript 优化的代码示例:


const moisture = response.getMoisture()
?? response.getMoisture_10()
?? response.getMoisture_20()
?? response.getMoisture_30()
?? response.getMoisture_40()
?? null;

在这个优化的版本中,我们使用了空值合并操作符 ?? 来逐个检查湿度值,并返回第一个非空值。如果所有的湿度值都为空,则返回 null

这种方式利用了 TypeScript 提供的语言特性,使得代码更加简洁和易于阅读。