[Typescript] handle event.target type in Form

Zhentiw發表於2024-07-29

The error we encountered in this challenge was that the EventTarget | null type was incompatible with the required parameter of type HTMLFormElement. The problem stems from the fact that these types don't match, and null is not permitted:

const data = new FormData(e.target); // red squiggly line under e.target

// hovering over e.target shows:
Argument of type 'EventTarget | null' is not assignable to parameter of type 'HTMLFormElement | undefined'.
Type 'null' is not assignable to type 'HTMLFormElement | undefined'.

Resolving the Error

First and foremost, it's necessary to ensure e.target is not null.

We can use the as keyword to recast e.target to a specific type.

However, if we recast it as EventTarget, an error will continue to occur:

const data = new FormData(e.target as EventTarget); // red squiggly line under `e.target as EventTarget`

The error message states that the argument of type EventTarget is not assignable to the parameter of type HTMLFormElement:
Since we know that the code works at runtime and has tests covering it, we can force e.target to be of type

const data = new FormData(e.target as HTMLFormElement);

Optionally, we can create a new variable, target, and assign the casted value to it:

const target = e.target as HTMLFormElement;
const data = new FormData(target);

Either way, this change resolves the error and target is now inferred as an HTMLFormElement and the code functions as expected.

相關文章