【问题标题】:How should I approach tslint no-null-keyword on frontend?我应该如何在前端处理 tslint no-null-keyword?
【发布时间】:2019-06-03 03:51:33
【问题描述】:

我在我的项目中启用了 tslint。我还在我的配置中添加了no-null-keyword。我正在使用 node.js,所以我在前端和后端都使用 typescript。所以在后端 no-null-keyword 不是问题。我可以轻松地将所有空值更改为未定义,但是当涉及到前端时,系统默认使用空值,这使我很难从空值变为未定义。

例如localStorage.getItem(nicknameId) 返回string | null

许多其他函数返回一个可能的 null 并且在 lib.es6.d.ts 中未定义。

readonly firstElementChild: Element | null;
readonly lastElementChild: Element | null;
readonly nextElementSibling: Element | null;
readonly previousElementSibling: Element | null;

我最好的想法是仅在后端使用此规则。但是前端将同时具有空值和未定义值,这将增加错误的机会。那么我应该如何处理呢?

【问题讨论】:

    标签: javascript typescript null eslint tslint


    【解决方案1】:

    在我们的项目中,我们使用一种方法来检查 undefinednull,而不是使用真/假检查并直接检查 undefinednull,除非存在语义差异 ofc .:

    export function isPresent<T>(value: T | null | undefined): value is T {
        return value !== undefined && value !== null;
    }
    

    这个方法会这样使用

    if(isPresent(localStorage.getItem(nicknameId))) {...}
    

    【讨论】:

      【解决方案2】:

      如果你的问题是你不能像这样严格地检查它:

      if (localStorage.getItem(nicknameId) !== null)
      

      你可以像这样错误地检查它:

      if (localStorage.getItem(nicknameId))
      

      如果由于0'' 等原因上述方法不起作用,您可以粗略地检查一下undefined(这“捕获”了undefinednull):

      if (localStorage.getItem(nicknameId) != undefined)
      

      【讨论】:

        猜你喜欢
        • 2011-07-22
        • 2021-10-18
        • 1970-01-01
        • 2019-07-19
        • 2018-03-23
        • 2016-09-26
        • 2020-06-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多