Type 'null' is not assignable to type 'HTMLInputElement' ReactJs

后端 未结 3 1524
粉色の甜心
粉色の甜心 2021-02-19 01:28

I am trying to reference data into reactJS along with typescript. While doing this I am getting below error

Type \'null\' is not assignable to type \'HTMLInputEl         


        
3条回答
  •  无人共我
    2021-02-19 01:45

    This is, indeed, caused by you correct and commendable use of:

    "strict": "true"
    

    Which sets a few rules including the all important:

    "strictNullChecks": "true"

    Handling Potential Nulls

    The correct way to handle this is to check that the element isn't in fact null, because almost every method you use to query an element may fail to find one.

    In the example below, the if-statement acts as a type guard, so the type of HTMLElement | null is narrowed to just HTMLElement.

    const elem = document.getElementById('test');
    
    if (elem) {
      elem.innerHTML = 'Type here is HTMLElement, not null';
    }
    

    Handling HTML Element Types

    To narrow the type from HTMLElement to HTMLInputElement, you can take an "I know better" approach and use a type assertion (making a class of subtle errors possible):

    const example =  elem;
    

    Or you can use a custom type guard to do it properly, the below example takes HTMLElement | null and narrows it to HTMLInputElement if it isn't null, and has the correct tag name:

    function isInputElement(elem: HTMLElement | null): elem is HTMLInputElement {
      if (!elem) {
        // null
        return false;
      }
    
      return (elem.tagName === 'INPUT')
    }
    

    The updated type guard call looks like this:

    const elem = document.getElementById('test');
    
    if (isInputElement(elem)) {
      console.log(elem.value);
    }
    

提交回复
热议问题