WebSocket and Real-Time Message Typing
What you'll learn: How to type WebSocket messages and events to ensure both client and server agree on the exact shape of data being transmitted in real-time.
The Communication Contract Problem
When building real-time applications with WebSockets, you're establishing a persistent connection where messages flow in both directions. Unlike REST APIs where you control request/response shapes through function signatures, WebSocket messages are just strings or binary data — raw, untyped payloads. Without proper typing, you can easily send the wrong message structure from the client, or mishandle incoming server messages.
Think of WebSocket typing like agreeing on a language before a phone conversation. Both parties need to understand what "hello" means, what fields a "chat message" contains, and what a "user joined" event looks like. TypeScript lets you enforce this agreement at compile time.
Typing Message Structures
You define discriminated unions for all possible message types:
type ClientMessage =
| { type: 'join'; username: string }
| { type: 'message'; text: string }
| { type: 'typing'; isTyping: boolean };
type ServerMessage =
| { type: 'welcome'; userId: string }
| { type: 'userJoined'; username: string }
| { type: 'chatMessage'; from: string; text: string; timestamp: number }
| { type: 'userTyping'; username: string };
Each message has a type discriminant property, making them perfect for exhaustive checking and narrowing.
Type-Safe Message Sending
function sendMessage(ws: WebSocket, message: ClientMessage): void {
ws.send(JSON.stringify(message));
}
// Type-safe calls
sendMessage(ws, { type: 'join', username: 'Alice' }); // ✓
sendMessage(ws, { type: 'message', text: 'Hello' }); // ✓
// sendMessage(ws, { type: 'join' }); // ✗ Missing username
Type-Safe Message Receiving
function handleServerMessage(data: string): void {
const message: unknown = JSON.parse(data);
// Runtime validation would happen here
// For now, we'll assert the type
const validated = message as ServerMessage;
switch (validated.type) {
case 'welcome':
console.log(`Connected with ID: ${validated.userId}`);
break;
case 'userJoined':
console.log(`${validated.username} joined`);
break;
case 'chatMessage':
console.log(`[${validated.from}]: ${validated.text}`);
break;
case 'userTyping':
console.log(`${validated.username} is typing...`);
break;
}
}
Notice we parse to unknown first (safe), then validate — combining runtime safety with type safety.
Shared Types in Full-Stack Applications
The real power comes from sharing these message type definitions between client and server in a monorepo:
// shared/messages.ts
export type ClientMessage = /* ... */;
export type ServerMessage = /* ... */;
// Both server and client import from the same file
// ensuring perfect synchronization
When you add a new message type on the server, the client code immediately shows type errors anywhere the new variant isn't handled — your type system becomes your API contract enforcer.
Key Takeaway: Typing WebSocket messages with discriminated unions creates a compile-time contract between client and server, catching message structure mismatches before they cause runtime bugs in production.