【问题标题】:How to work around Object is possibly 'null'.ts(2531) error in TypeScript?如何解决 TypeScript 中的 Object is possible is 'null'.ts(2531) 错误?
【发布时间】:2019-10-27 05:12:55
【问题描述】:

我见过How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?。和其他东西。这不是重复的!

有 3 种不同的方法可以抑制这个错误。我不想要什么。我也不想禁用严格的空类型。我想要一个适当的解决方案来正确编码。

我可以创建一个与HTMLElementElement 相同的新类型,只是不带null 吗?如果它们实际上为空并且我只是抑制 TS 中的警告,那么在运行时会发生什么。这感觉就像一个可怕的解决方法。

function insertAfter( newNode: HTMLElement, referenceNode: Element ) : void {

    referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}

这不起作用。 TS linter 不够聪明,无法检测到这一点:

function insertAfter( newNode: HTMLElement, referenceNode: Element ) : void {

    if ( null === referenceNode ) {
        throw Error( 'ref node is null');
    }

    referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}

在这里找到这个:https://rules.sonarsource.com/typescript/RSPEC-2966 也不起作用。

function insertAfter( newNode: HTMLElement, referenceNode: Element ) : void {
    if ( referenceNode ) {
        referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
    }

    throw Error( 'ref node is null');
}

我是 TypeScript 的新手,但这是最烦人的事情。我希望有一个我还没有找到的解决方案。

【问题讨论】:

  • "这不起作用。TS linter 不够聪明,无法检测到这一点:" 它。它不是在抱怨referenceNode,而是在抱怨referenceNode.parentNode,它可能是null。检查playground 并记下该消息及其来源。
  • 是的,null === referenceNode.parentNode 是你应该做的测试。您知道referenceNode 不是null,因为insertAfter 不接受referenceNodenull 值。但是parentNode 可能是null
  • 您对父节点是正确的。我正在使用 VScode,它实际上在许多情况下都强调了这两个错误并显示了这两个错误。如果我在其中放入没有意义的代码,它有时只会在“不存在的类型从不”的点后面加下划线。这似乎是 linter 中的一个错误。

标签: typescript null isnull


【解决方案1】:

正如评论中的人指出的那样,实际上是关于.parentNode。但是 VScode 对此有问题,它显示了两个错误。

此解决方案有效:

function insertAfter( newNode: HTMLElement, refNode: Element ) : void {

    if ( null === refNode.parentNode ) {
        throw Error( 'refNode.parentNode is null');
    }

    refNode.parentNode.insertBefore( newNode, refNode.nextSibling );
}

【讨论】:

    猜你喜欢
    • 2020-12-18
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 2017-10-14
    相关资源
    最近更新 更多