Working with Forms
In this page:
Creating a Typed Form
Typing a form element as HTMLFormElement gives you access to its .elements collection and its submit/reset methods with proper autocomplete, instead of treating it as a generic, undifferentiated element.
Example: Creating a Typed Form
const form = document.createElement("form") as HTMLFormElement;
console.log(form.elements.length, typeof form.submit);
Handling Form Submission
Handling form submission means listening for the submit event and calling event.preventDefault() inside a handler typed to receive a SubmitEvent, which stops the browser's default full-page reload.
Example: Handling Form Submission
const form = document.createElement("form");
form.addEventListener("submit", (event: SubmitEvent) => {
event.preventDefault();
console.log("Submission prevented");
});
form.dispatchEvent(new SubmitEvent("submit", { cancelable: true }));
Reading Input Values
Reading input values safely means narrowing event.target to HTMLInputElement first, since the base event type has no .value property — skipping this narrowing is a very common source of TypeScript form-handling errors.
Example: Reading Input Values
const input = document.createElement("input");
input.value = "hello";
input.addEventListener("input", (event: Event) => {
const target = event.target as HTMLInputElement;
console.log(target.value);
});
input.dispatchEvent(new Event("input"));
FormData
The FormData API lets you collect every named field's value from a submitted form at once, and typing it correctly means knowing its .get() method returns FormDataEntryValue | null, not a bare string.
Example: FormData
const form = document.createElement("form");
form.innerHTML = '<input name="username" value="ravi">';
const data = new FormData(form);
const value: FormDataEntryValue | null = data.get("username");
console.log(value);
Form Validation
Form validation in TypeScript usually combines HTML's built-in constraint attributes (like required) with typed custom logic that runs on submit, since the compiler alone can't guarantee a user actually filled a field in correctly.
Example: Form Validation
const input = document.createElement("input");
input.required = true;
input.value = "";
function isValid(el: HTMLInputElement): boolean {
return !el.required || el.value.trim().length > 0;
}
console.log(isValid(input));
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: