【发布时间】:2019-10-27 05:12:55
【问题描述】:
我见过How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?。和其他东西。这不是重复的!
有 3 种不同的方法可以抑制这个错误。我不想要什么。我也不想禁用严格的空类型。我想要一个适当的解决方案来正确编码。
我可以创建一个与HTMLElement 和Element 相同的新类型,只是不带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不接受referenceNode的null值。但是parentNode可能是null。 -
您对父节点是正确的。我正在使用 VScode,它实际上在许多情况下都强调了这两个错误并显示了这两个错误。如果我在其中放入没有意义的代码,它有时只会在“不存在的类型从不”的点后面加下划线。这似乎是 linter 中的一个错误。
标签: typescript null isnull