How to work around Object is possibly 'null'.ts(2531) error in TypeScript?

牧云@^-^@ 提交于 2021-01-29 21:13:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!