首页 > 解决方案 > 如何使用 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);
    }

标签: typescriptnested-ifunion-types

解决方案


你可以使用 LoDash。_.get将自动进行错误处理。如果enull/ 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/见页面底部)。


推荐阅读