Supporters
JOIN MY SPONSORS

Typed Chat

Different message types are routed to different handlers. Try sending a chat vs an emote to see type routing in action.

You are .... Open another tab to chat with yourself.

no messages yet...
chat.ts
import { connect } from 'itty-sockets'

type ChatMessage = { type: 'chat', text: string }
type EmoteMessage = { type: 'emote', action: string }

const chat = connect('ittysockets.com:demos/typed-chat', {
  announce: true,
  echo: true,
  as: '...',
})
  .on('join', ({ alias }) => {
    // display the join message
  })
  .on('leave', ({ alias }) => {
    // display the leave message
  })
  // type routing — each type gets its own handler
  .on<ChatMessage>('chat', ({ alias, text }) => {
    // "Kevin: hello!"
  })
  .on<EmoteMessage>('emote', ({ alias, action }) => {
    // "*Kevin waves*"
  })

chat.send<ChatMessage>({ type: 'chat', text: 'hello!' })
chat.send<EmoteMessage>({ type: 'emote', text: 'waves' })

Alternatively, you can use an event map to type the connection while keeping your downstream code cleaner:

chat.ts (with event map)
import { connect } from 'itty-sockets'

type ChatMessage = { type: 'chat', text: string }
type EmoteMessage = { type: 'emote', action: string }

type Events = {
  chat: ChatMessage
  emote: EmoteMessage
}

const chat = connect<Events>('ittysockets.com:demos/typed-chat', {
  announce: true,
  echo: true,
  as: '...',
})
  .on('chat', ({ alias, text }) => { /* ... */ })
  .on('emote', ({ alias, action }) => { /* ... */ })

chat.send({ type: 'chat', text: 'hello!' })
chat.send({ type: 'emote', action: 'waves' })