typescript
/

TypeScript Events

Last Sync: Today

On this page

10
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

typescript

TypeScript Events

What are Events?

Events are actions or occurrences that happen in the browser, such as clicks, inputs, or keyboard actions.

Basic Event Handling

TypeScriptRead-only
1
const btn = document.querySelector('button') as HTMLButtonElement;

btn.addEventListener('click', () => {
  console.log('Clicked');
});

Typed Event

TypeScriptRead-only
1
btn.addEventListener('click', (e: MouseEvent) => {
  console.log(e.clientX);
});

Input Event

TypeScriptRead-only
1
const input = document.querySelector('input') as HTMLInputElement;

input.addEventListener('input', (e: Event) => {
  console.log(input.value);
});

Keyboard Event

TypeScriptRead-only
1
document.addEventListener('keydown', (e: KeyboardEvent) => {
  console.log(e.key);
});

Event Types

EventType
clickMouseEvent
inputEvent
keydownKeyboardEvent
submitSubmitEvent

Prevent Default

TypeScriptRead-only
1
form.addEventListener('submit', (e: SubmitEvent) => {
  e.preventDefault();
});

Best Practices

  • Use proper event types
  • Avoid using any
  • Handle null elements
  • Use type assertions carefully

Common Mistakes

  • Not typing events properly
  • Ignoring null checks
  • Using wrong event types
  • Overusing any type

Conclusion

TypeScript events provide strong typing for browser interactions, improving safety and developer experience.

Try it yourself

document.addEventListener('click', (e: MouseEvent) => console.log(e.clientX));

Test Your Knowledge

Q1
of 3

Click event type?

A
Event
B
MouseEvent
C
KeyboardEvent
D
SubmitEvent
Q2
of 3

Keyboard event?

A
MouseEvent
B
Event
C
KeyboardEvent
D
InputEvent
Q3
of 3

Prevent default method?

A
stop()
B
preventDefault()
C
cancel()
D
end()

Frequently Asked Questions

What is event?

User or system action.

Mouse event type?

MouseEvent.

Prevent default?

Stops default behavior.

Previous

ts dom

Next

ts fetch

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.