Narrowing generic type from function argument
06:24 06 Oct 2025

I need to cover with types this code:

interface MessageData {
  offscreen: {
    start: { streamId: string }
    setVolume: { volume: string }
    stop: void
  }
  service_worker: {
    test: { testData: number }
  }
}

function addEventListener(msg) {
  if (msg.target !== 'offscreen') return

  if (msg.action === 'start') start(msg.data.streamId)
  else if (msg.action === 'setVolume') setVolume(msg.data.volume)
  else if (msg.action === 'stop') stop()
}

And this is what I came to

function addEventListener(msg: { target: T, action: A, data: D }) {
  if (msg.target !== 'offscreen') return

  if (msg.action === 'start') start(msg.data.streamId)
  else if (msg.action === 'setVolume') setVolume(msg.data.volume)
  else if (msg.action === 'stop') stop()
}

For example, this code works, and the sendMessage method correctly resolves types when using the function.

function sendMessage(target: T, action: A, data?: D) {
  return chrome.runtime.sendMessage({ target, action, data })
}

And I don't understand why this doesn't happen in addEventListener.

typescript typescript-generics