[Typescript] Generics in Function Overloads

Here's a function called returnWhatIPassInExceptFor1:

function returnWhatIPassInExceptFor1(t: unknown): unknown {
  if (t === 1) {
    return 2;
  }
  return t;
}

When I pass in anything other than 1, the function should return what I pass in (as the name suggests).

For example, if I pass in ab, or c, the function should return ab, or c respectively.

However, when I pass in 1, the result should be of type 2.

 

Solution:

function returnWhatIPassInExceptFor1(t: 1): 2;
function returnWhatIPassInExceptFor1<T>(t: T): T;
function returnWhatIPassInExceptFor1<T1, T2>(t: T1): T2;
function returnWhatIPassInExceptFor1(t: unknown): unknown {
  if (t === 1) {
    return 2;
  }
  return t;
}

 

So for the frist one:

function returnWhatIPassInExceptFor1(t: 1): 2;

it('Should return the type 2 when you pass in 1', () => {
  const result = returnWhatIPassInExceptFor1(1);

  type test1 = Expect<Equal<typeof result, 2>>;
});

 

For the second one:

function returnWhatIPassInExceptFor1<T>(t: T): T;

it('Otherwise, should return what you pass in', () => {
  const a = returnWhatIPassInExceptFor1('a');
  const b = returnWhatIPassInExceptFor1('b');
  const c = returnWhatIPassInExceptFor1('c');

  type tests = [
    Expect<Equal<typeof a, 'a'>>,
    Expect<Equal<typeof b, 'b'>>,
    Expect<Equal<typeof c, 'c'>>
  ];
});

 

For the third one:

function returnWhatIPassInExceptFor1<T1, T2>(t: T1): T2;

it('Should accepts two generic slot, pass T1 return T2', () => {
  const d = returnWhatIPassInExceptFor1<'a', 'd'>('a');

  type tests = [Expect<Equal<typeof d, 'd'>>];
});

So function overload, it able to tell which overload to use when you give generic type returnWhatIPassInExceptFor1<'a', 'd'>

 

posted @   Zhentiw  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2022-02-02 [AWS] AWS Control Tower for multi accounts
2018-02-02 [Typescript] Build Method decorators in Typescript
2017-02-02 [Javascript] Write a function pipeline
2017-02-02 [React] Pass Data To Event Handlers with Partial Function Application
2016-02-02 [Cycle.js] Read effects from the DOM: click events
2016-02-02 [Cycle.js] Introducing run() and driver functions
2016-02-02 [Cycle.js] Customizing effects from the main function
点击右上角即可分享
微信分享提示