Issue
I have the following form:
<form id="search" method="post">
<input type="text" name="query" id="search-field"/>
</form>
And I want to attach a submit event listener in TypeScript:
document.getElementById("search").addEventListener("submit", (event: SubmitEvent) => {
event.preventDefault();
console.log(event.target.children.query.value);
});
However typescript gives me the following error:
error TS2339: Property 'children' does not exist on type 'EventTarget'.
20 console.log(event.target.children.query.value);
How can I tell TypeScript that the target of the submit event is a form, which has a valid children.query element?
Solution
Since the event can happen on any HTML element it is tricky for TS to figure out on which element the event was triggered. You can help it by using a type assertion, it is not fancy and it feels "forced" but it works if you know that your event will be triggered only on a given HTML element.
With this strategy your code would be something like (after checking types I changed a little bit since the types prompted me to this usage)
document.getElementById("search").addEventListener("submit", (event: SubmitEvent) => {
const form = event.target as HTMLFormElement;
event.preventDefault();
console.log((form.children.namedItem("search-field") as HTMLInputElement).value);
});
Note that the return value of namedItem is of type Element which is too generic, that's why I had to cast it to HTMLInputElement that in this case contains a value
Answered By - Daniel Rodríguez Meza
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.