DEV Community

Tony Ngan
Tony Ngan

Posted on

TS#1 Type-safe publish event function

When we design an event, the descriptors are simply the type and payload, where payload is composed of the properties describing what's happened in the system.

enum MyEvent {
  FOO = 'FOO',
  BAR = 'BAR'
}

interface MyEventPayload {
  [MyEvent.FOO]: {
    prop1: string;
    prop2: string;
  }
}

async function sendEvent<T extends keyof MyEventPayload>(type: T, payload: MyEventPayload[T]): Promise<void> {
  // implementation
}

// @ts-expect-error
sendEvent();
// @ts-expect-error
sendEvent(MyEvent.FOO);
// @ts-expect-error
sendEvent(MyEvent.FOO, {});
// @ts-expect-error
sendEvent(MyEvent.FOO, { prop1: 'x', prop2: 'y', prop3: 'z' });

// works!
sendEvent(MyEvent.FOO, { prop1: 'x', prop2: 'y' });
Enter fullscreen mode Exit fullscreen mode

By taking advantage of the generics, we can easily construct a type-safe function where the type of arguments are dependent on each other.

Top comments (0)