Typescript - Solid.js <select> onchange event: Property 'value' does not exist on type 'EventTarget'

3k views Asked by At

In the following example, if I don't do ?. for the event.target.value, typescript has the error Object is possibly null. With the ?. I get the error Property 'value' does not exist on type 'EventTarget'.

What do I need to do to get the type of the event for the onchange to be correct?

import { createSignal } from "solid-js";

export default function Cards() {
  const [cellsWide, setCellsWide] = createSignal(0);

  return (
    <>
      <div>
        <select
          name="cellsWide"
          onChange={(e: Event) => {
            console.log(e?.target?.value);
          }}
        >
          <option value="5">5</option>
          <option value="3">3</option>
        </select>
      </div>
      <div>This is where cards goes - {cellsWide()}</div>
    </>
  );
1

There are 1 answers

1
FoolsWisdom On BEST ANSWER

The event handler should look like this:

<select
  name="cellsWide"
  onChange={(e) => {
    console.log(e.currentTarget.value);
  }}
>

The difference between target and currentTarget is explained on MDN here. target is the element that triggered the event, currentTarget is the element the handler is on. This means that strictly speaking, target might not be the element you defined the handler on, it might not even be an HTMLElement. Using currentTarget is therefore the safe alternative.