Home > Enterprise >  file input null check erroring Object is possibly 'null' in typescript
file input null check erroring Object is possibly 'null' in typescript

Time:07-10

I am trying to check against input file being null in typescript. the problem is that (if condition is erroring out) telling me Object is possibly 'null'. how to check against null for this particular case ?

const input = document.querySelector('#image') as HTMLInputElement;

const loadImage = () =>{
if (input.files[0]['type']) {
    const fileType = input?.files![0]['type'];
   }
}
<input id="image" ref={inputRef} accept="image/*" type="file" onChange={loadImage} />

CodePudding user response:

You can add a condition to check if the input element is null (or undefined) :

if (input && input.files[0]['type']) {
    const fileType = input.files![0]['type'];
}

CodePudding user response:

you only want to return your JSX should there be an input to pass:

{ inputRef && <input ref={inputRef} {…code} /> }

  • Related