ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Discriminated Rendering: Event Handler Types

TSX

Goal -- WPM

Ready
Exercise Algorithm Area
1type ClickEvent = {
2type: 'click';
3x: number;
4y: number;
5};
6
7type KeyPressEvent = {
8type: 'keypress';
9key: string;
10};
11
12type MouseMoveEvent = {
13type: 'mousemove';
14deltaX: number;
15deltaY: number;
16};
17
18type AppEvent = ClickEvent | KeyPressEvent | MouseMoveEvent;
19
20function handleEvent(event: AppEvent): string {
21switch (event.type) {
22case 'click':
23return `Clicked at (${event.x}, ${event.y})`;
24case 'keypress':
25return `Key pressed: ${event.key}`;
26case 'mousemove':
27return `Mouse moved by (${event.deltaX}, ${event.deltaY})`;
28default:
29// This should ideally be unreachable with exhaustive checks
30const _exhaustiveCheck: never = event;
31return `Unknown event type: ${_exhaustiveCheck}`;
32}
33}
34
35export { handleEvent };
Algorithm description viewbox

Discriminated Rendering: Event Handler Types

Algorithm description:

This function demonstrates discriminated unions in TypeScript to handle different event types. Each event type has a common `type` property that acts as a discriminant. The `handleEvent` function takes an `AppEvent` (a union of all possible event types) and uses a `switch` statement on the `type` property to safely access event-specific payloads. This pattern is crucial for managing diverse data structures within a single type, common in UI event handling or state management.

Algorithm explanation:

The `handleEvent` function leverages discriminated unions to achieve type-safe handling of different event types. Each event type (`ClickEvent`, `KeyPressEvent`, `MouseMoveEvent`) has a literal `type` property that uniquely identifies it. The `AppEvent` type is a union of these specific event types. The `switch` statement on `event.type` allows TypeScript to narrow down the type of `event` within each `case` block, ensuring that only the correct properties (e.g., `x`, `y` for `click`) are accessed. The `default` case with `never` is a common pattern for ensuring exhaustiveness, causing a compile-time error if a new event type is added to the union but not handled in the switch. Time complexity is O(1) as it's a simple switch. Space complexity is O(1).

Pseudocode:

Define ClickEvent type with type='click', x, y.
Define KeyPressEvent type with type='keypress', key.
Define MouseMoveEvent type with type='mousemove', deltaX, deltaY.
Define AppEvent as a union of ClickEvent, KeyPressEvent, MouseMoveEvent.
Create handleEvent function accepting AppEvent.
Use switch statement on event.type:
  Case 'click': return formatted string with x, y.
  Case 'keypress': return formatted string with key.
  Case 'mousemove': return formatted string with deltaX, deltaY.
  Default case: handle unknown event type (e.g., throw error or return default string).