Event Targets in Event Handlers
What you'll learn: How to correctly assert event.target types in event handlers when you know exactly which element triggered the event.
The Problem with Generic Event Targets
When you write event handlers in TypeScript (especially for DOM events), event.target has a very generic type: EventTarget | null. This type doesn't know what kind of element triggered the event, so you can't safely access element-specific properties like value on an input or checked on a checkbox.
function handleInput(event: Event) {
// Error: Property 'value' does not exist on type 'EventTarget'
console.log(event.target.value);
}
TypeScript is being cautious here because technically any element could have triggered the event. But in practice, you often know exactly what element it is.
Asserting to the Specific Element Type
When you're certain about the element type (because you attached the handler to a specific element), you can use a type assertion to tell TypeScript what you know:
function handleInput(event: Event) {
const target = event.target as HTMLInputElement;
console.log(target.value); // ✓ Works! 'value' exists on HTMLInputElement
}
This is safe when you know the handler is only attached to input elements. The assertion bridges the gap between TypeScript's generic type and your runtime reality.
Common Element Type Assertions
Different elements need different types:
// Input elements
const input = event.target as HTMLInputElement;
input.value;
// Button elements
const button = event.target as HTMLButtonElement;
button.disabled;
// Form elements
const form = event.target as HTMLFormElement;
form.submit();
// Checkbox or radio
const checkbox = event.target as HTMLInputElement;
checkbox.checked;
Key Takeaway: Use as to assert event.target to the specific element type (like HTMLInputElement) when you know which element triggered the event, enabling access to element-specific properties safely.