1

I am fairly new to TypeScript and have just created a change handler function to take in the event as the parameter to set the value, i.e. event.target.value. I have currently set this to any but thinking there must be a correct type for this?

This is my method which is within a functional react component:

const handleChange = (event: any) => {
  setValue(event.target.value);
};
Sprose
  • 1,255
  • 1
  • 16
  • 20
  • It depends if you are listening to the original event or an event handler. If you are using reactjs (as it seems), the event could be of type React.ChangeEvent. You can also console.log(event) and look for the type in its properties. – Marcelo Viana Sep 22 '20 at 07:59
  • Are you using React? https://stackoverflow.com/questions/42081549/typescript-react-event-types – jonrsharpe Sep 22 '20 at 08:01
  • Yes using react – Sprose Sep 22 '20 at 08:46
  • When I console log it says it is a SyntheticEvent - although that is not a valid type.. – Sprose Sep 22 '20 at 08:53

2 Answers2

2

Basic DOM Events

Basic DOM Events are defined in a file called lib.dom.d.ts. Search for 'interface Event' and you'll find the typings for the definition in the DOM specification.

Here is an excerpt:

/** An event which takes place in the DOM. */
interface Event {

/**
 * Returns the object to which event is dispatched (its target).
 */
readonly target: EventTarget | null;

// many, many more properties
}

As you can see, this interface will satisfy your code. But be aware that 'target' can be null so respect this in your handleChange function:

const handleChange = (event: Event) => {

  const target = event.target; // Event | null

  if (target === null) {
     throw new Error('target can not be null');
  }

  // targets type is now Event

  setValue(target.value); // target.value is of type EventTarget
};

React Events

Others asumed that you're using react. In this case have a look at the typings here. You'll find something called 'SyntheticEvent' which is "a cross-browser wrapper around the browser’s native event".

Excerpt:

interface BaseSyntheticEvent<E = object, C = any, T = any> {
    nativeEvent: E;
    currentTarget: C;
    target: T;
    
    // many more properties
}

interface SyntheticEvent<T = Element, E = Event> extends BaseSyntheticEvent<E, EventTarget & T, EventTarget> {}

Which satisfies your code as well.

Read more about React Events here.

CKE
  • 460
  • 3
  • 14
  • Well constructed answer. I added the interface and used the BaseSyntheticEvent in place of the any in my code example. Worked a charm. – Sprose Sep 22 '20 at 08:59
1

If you use ChangeEvent and supply the element type you are listening to, you can avoid the extra logic of checking to make sure target or currentTarget is null.

Example:

const handleChange = ({
    currentTarget,
  }: ChangeEvent<HTMLInputElement>) => {
    const { name, value } = currentTarget;
papiro
  • 2,158
  • 1
  • 20
  • 29