2

Please see this minimum example below:

/** @jsx h */
import { h, FunctionalComponent } from 'preact';

const Test: FunctionalComponent = () => {
  return (
    <select
      value="1"
      onChange={(event) => {
        console.log(event.target.value);
      }}
    >
      <option value="1">1</option>
      <option value="2">2</option>
    </select>
  );
};

image showing unsafe access to object field

How do I resolve the error where it says Object is possibly 'null'?

2 Answers 2

2

This is a "TypeScript safety check" to inform you that event.target may be null, which would cause access to event.target.value to throw an error at run-time.

This warning/error can be silenced by using the "non-null assertion operation":

<select value="1" onChange={(event) => {
    /* Add ! after target to state that "event.target!" is defined and 
       that value field can be safely accessed. This is a non-null 
       assertion */
    console.log(event.target!.value);
}}>

Or by checking that event.target is defined before accessing it:

<select value="1" onChange={(event) => {

    const { target } = event;
    if(target) {
        /* The ! is not needed seeing target is dedeuced as being defined */
        console.log(target.value);
    }
}}>
Sign up to request clarification or add additional context in comments.

4 Comments

Neither of these solutions work for me. typescript 3.5.3 The non-null assertion operator has no affect and even if my condition explicitly says target !== null, I still get the "object is possibly 'null'" error.
@Vince that's strange - can you please provide a snippet of the code that's causing the problem (ie via a git gist)?
@Vince please verify the type of event you are defining in your event handler. if it is not React.ChangeEvent then you might still get error unless you check for event.target && event.target.value before using.
You can try using the check: if (event.target.files)
0

Make sure to check event.target.value before accessing it. See below

    <select value="1" onChange={(event) => {
    event.target.value? console.log(event.target.value):null;
}}

I had a similar issue when selecting file

<input
  type="file"
  onChange={(event: React.ChangeEvent<HTMLInputElement>): void => {
    formik.setFieldValue(
      "file",
      (event?.target.files && event?.target?.files[0]) ?? ""
    );
    formik.setFieldValue(
      "fileName",
      (event?.target.files && event?.target?.files[0].name) ?? ""
    );
  }}
/>;

Comments

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.