What's the difference using 'event' as parameter in these formats?

Viewed 64

There's an event handler function in my project, which takes 'event' as the only parameter.There's only one format working in the project. E.g. If a line of console.log is added to the function body, it would be displayed only in the first format.

The framework is an internal one, based on React, also uses web components.

What are the difference between these formats?

All three formats have the same function body.

Format 1, working in my project:

public sendClickEvent = ({ event: e }) => {
  e.preventDefault();
  // handler body
}

Format 2, not working in my project:

public sendClickEvent = (event: any) => {
   event.preventDefault();
  // handler body
}

Format 3, not working in my project:

public sendClickEvent(event: any): void {
   event.preventDefault();
  // handler body
}
1 Answers

It looks like sendClickEvent is called with an object, which has a property named event. As a result:

public sendClickEvent = ({ event: e }) => {
  e.preventDefault();

works because { event: e } destructures the event property from the object argument and puts the event into a variable named e. But

public sendClickEvent = (event: any) => {
   event.preventDefault();

won't work because the argument is an object wrapper around it, not the event itself. You'd need something like

public sendClickEvent = (obj) => {
   obj.event.preventDefault();

Since this is TypeScript, I'd also highly recommend not using any, since that effectively disables type-checking, defeating the whole purpose of using TypeScript. Figure out the exact type the function should be called with, and type the function as that, so that you don't have to use any anywhere. Perhaps something along the lines of

public sendClickEvent = ({ event: e }: { event: React.MouseEvent }) => {
  e.preventDefault();
Related