[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 @   Zhentiw  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-02-18 [Javascript] Primitive value are immutable
2020-02-18 [ML] 2. Introduction to neural networks
2020-02-18 【逻辑思维】同一律:白马到底是不是马
2019-02-18 [NPM] Avoid Duplicate Commands by Calling one NPM Script from Another
2019-02-18 [Algorithm] Dynamic programming: Find Sets Of Numbers That Add Up To 16
点击右上角即可分享
微信分享提示