[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 @ 2023-02-02 01:15  Zhentiw  阅读(27)  评论(0编辑  收藏  举报