[Typescript] Creating a Dynamic Function with Variable Arguments

import { it } from 'vitest';

interface Events {
  click: {
    x: number;
    y: number;
  };
  focus: undefined;
}

type LookUpEvents<K extends keyof Events> = Events[K] extends undefined
  ? false
  : true;

export const sendEvent = <TEvent extends keyof Events>(
  event: TEvent,
  ...args: LookUpEvents<TEvent> extends false
    ? [payload?: undefined]
    : [payload: Events[TEvent]]
) => {
  // Send the event somewhere!
};

it('Should force you to pass a second argument when you choose an event with a payload', () => {
  // @ts-expect-error
  sendEvent('click');

  sendEvent('click', {
    // @ts-expect-error
    x: 'oh dear',
  });

  sendEvent(
    'click',
    // @ts-expect-error
    {
      y: 1,
    }
  );

  sendEvent('click', {
    x: 1,
    y: 2,
  });
});

it('Should prevent you from passing a second argument when you choose an event without a payload', () => {
  sendEvent('focus');

  sendEvent(
    'focus',
    // @ts-expect-error
    {}
  );
});

 

posted @ 2023-02-18 16:15  Zhentiw  阅读(14)  评论(0编辑  收藏  举报