0

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} />

1
  • You should be able to do it by placing a ? After the variable you expect to be null. Commented Jul 10, 2022 at 1:53

2 Answers 2

1

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'];
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

2 Comments

run time error is after change happens to the input , so this jsx solution won't fix the issue, plus ref.current.. and i want the input on display this will hide it and cannot even add file to it if the ref is false at start!
I thought that was the point!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.