问题
I have seen How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?. And other things. This is not a duplicate!
There are like 3 different ways to suppress this error. I do not want what. I do not want to disable strict null types either. I want a proper solution to code this properly.
Can I create a new type that is the same as HTMLElement
and Element
just without null? What will happen at run-time if they are actually null and I just suppress the warning in TS. It feels like a horrible workaround.
function insertAfter( newNode: HTMLElement, referenceNode: Element ) : void {
referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}
This is not working. TS linter is not smart enough to detect this:
function insertAfter( newNode: HTMLElement, referenceNode: Element ) : void {
if ( null === referenceNode ) {
throw Error( 'ref node is null');
}
referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}
Found this here: https://rules.sonarsource.com/typescript/RSPEC-2966 also not working.
function insertAfter( newNode: HTMLElement, referenceNode: Element ) : void {
if ( referenceNode ) {
referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}
throw Error( 'ref node is null');
}
I am new to TypeScript but this is the most annoying thing. I hope there is a solution that I just did not find yet.
回答1:
It was actually about .parentNode
as the guys in the comment pointed out. But VScode is buggy about this, it shows both errors.
This solution works:
function insertAfter( newNode: HTMLElement, refNode: Element ) : void {
if ( null === refNode.parentNode ) {
throw Error( 'refNode.parentNode is null');
}
refNode.parentNode.insertBefore( newNode, refNode.nextSibling );
}
来源:https://stackoverflow.com/questions/58529845/how-to-work-around-object-is-possibly-null-ts2531-error-in-typescript