0

I want to define the type of a function from a union of types:

type MyEvent =
| { type: 'hello', payload: {} }
| { type: 'start', payload: { date: Date } }


type On<Event> = Event extends { type: infer EventType, payload: infer EventPayload }
  ? (type: EventType, callback: (payload: EventPayload) => void) => void
  : never

const on: On<MyEvent>
on('hello', (payload) => void)

but the compiler defines the type of the first argument as "never"

The On returns a type that seems good. I tried the raw type returned as well, with the same result:

type RawOn =
| ((type: "hello", callback: (payload: {}) => void) => void)
| ((type: "start", callback: (payload: { date: Date }) => void) => void)

const raw_on: RawOn
raw_on('hello', (payload) => void)

How can I define "a union type of function signature" ?

Playground

Frédéric Mascaro
  • 520
  • 1
  • 4
  • 17

1 Answers1

0

Thanks to @cherryblossom for the solution:

type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void)
  ? I
  : never

// --------------------------------------------------
  
type MyEvent =
| { type: 'hello', payload: {} }
| { type: 'start', payload: { date: Date } }


type On<Event> = UnionToIntersection<
  Event extends { type: infer EventType, payload: infer EventPayload }
    ? (type: EventType, callback: (payload: EventPayload) => void) => void
    : never
>

const init_on = (): On<MyEvent> => {}
const on = init_on()

// OK
on('hello', (payload: {}) => {})
on('start', (payload: { date: Date }) => {})

// ERROR (that is OK)
on('hello', (payload: { date: Date }) => {})
on('bad-event', (payload: {}) => {})

Playground

Frédéric Mascaro
  • 520
  • 1
  • 4
  • 17