Home > Mobile >  Payload type inference for events with a given type
Payload type inference for events with a given type

Time:11-18

I have a scenario where I have different events like the following:

type EventType = 'foo' | 'bar'

type Event = {
  type: 'foo',
  timestamp: number,
  payload: { a: number }
} | {
  type: 'bar',
  timestamp: number,
  payload: { b: string }
}

Then I have a listener like this:

on('foo', event => {
  // Here we should know that the type must be 'foo',
  // and therefore the payload has the shape {a: number}
  // but I don't know how to tell that to TS
})

I've tried a few different things, but so far all I've managed is for the compiler to stop compiling

  • Related