typescript - 如何使用 let x: type | 避免嵌套的 typescript if 语句 未定义 = 变量
问题描述
有没有更好的方法来处理类型检查?type2 当一个变量被定义为类型 | 类型2?例如,我有这个小代码片段:
if (e) {
let targetElement: Element | undefined = e.toElement;
if (targetElement) {
let medicineCategory: string | null = targetElement.textContent;
if (medicineCategory) {
$('#selected-medicine-info').text(medicineCategory);
}
}
}
在代码中对 !undefined 和 !null 进行大量检查似乎真的很不优雅,尤其是如果它嵌套得更深的话。
我决定了这个,这是一个更好的阅读,我可以很容易地看出 textContent 的值为 null:
let targetElement: Element | undefined = e.toElement;
if (targetElement) {
let medicineCategory: string | null = (targetElement.textContent !== null) ? targetElement.textContent : "null";
$('#selected-medicine-info').text(medicineCategory);
}
解决方案
你可以使用 LoDash。_.get
将自动进行错误处理。如果e
是null
/ undefined
,或者路径不存在,它将简单地返回一个默认值。如果您不提供默认值,它将返回undefined
.
// _.get takes an `object`, `path`, and `default`. Typescript will infer
// that the type is `string`, because the default is an empty string
// (thanks Lodash)
const medicineCategory = _.get(e, ['toElement', 'textContext'], '');
if (medicineCategory)
$('#selected-medicine-info').text(medicineCategory);
在此处查看更多信息:https ://lodash.com/docs/4.17.10#get
LoDash 是 npm 最依赖的库是有原因的。(https://www.npmjs.com/见页面底部)。
推荐阅读
- amazon-web-services - AWS Amplify 域重定向到另一个域
- javascript - 如何在另一个查询循环中执行查询循环
- javascript - Discord Bot 错误“MaxListenersExceededWarning”
- python - Selenium - Chromedriver filenotfound 错误消息
- python - 总结40m之类的时间列;1d 2h 20m;3h 10m
- python - Python中拟合参数分布的匹配矩不准确
- javascript - 使用登录表单获取帖子返回带有无效凭据的服务器错误 400
- css - 嵌入式字体系列无法在 ios 14 上正确呈现
- php - PHP 按键拆分数组 -> 值
- android - 滚动到屏幕外时从 RecyclerView 中消失的项目