在Typescript中,如何实现带有重载的裸功能接口?

时间:2017-07-29 08:39:18

标签: typescript

我正在使用Typescript 2.3.3

我正在尝试为我正在编写的一些代码创建一个很好的API,所以我正在尝试使用Typescript的泛型中的可能性。

我希望能够使用泛型类型调用函数,并使用该类型向用户显示选项,其中一些可能是具有不同签名的函数。

到目前为止,这是我的尝试。

我声明了一个带有两个裸函数签名的接口(我想向开发人员提供的两个选项):

interface api<T1> {

  <T2>(second: T2):  {
    first: T1
    second: T2;
  };

  <T2, T3>(second: T2, third: T3):  {
    first: T1
    second: T2;
    third: T3;
  };

}

我创建了一个包含每个函数签名实现的函数,使用传递给它的泛型类型参数:

const test = <TFirst>(first: TFirst) : api<TFirst> => {

  const impl1 = <T2>(second: T2) => ({
    first, second
  });

  const impl2 = <T2, T3>(second: T2, third: T3) =>({
    first, second, third
  });

  return ...?
};

但我不知道在哪里分配这些实现或如何创建符合api规范的返回对象。

这甚至可能吗?

1 个答案:

答案 0 :(得分:2)

这是可能的。你可以这样做:

interface api<T1> {

  <T2>(second: T2):  {
    first: T1;
    second: T2;
  };

  <T2, T3>(second: T2, third: T3):  {
    first: T1;
    second: T2;
    third: T3;
  };
};

function createApi<T1>(first: T1): api<T1> {

  function impl<T2>(second: T2): { first: T1; second: T2; };
  function impl<T2, T3>(second: T2, third: T3): { first: T1; second: T2; third: T3; };
  function impl<T2, T3>(second: T2, third?: T3): { first: T1; second: T2; third?: T3; } {
    if (third === undefined) {
      return { first, second };
    }
    return { first, second, third };
  }

  return impl;
}

const test = createApi<number>(1);
console.log(test(2));
console.log(test(2, 3));

createApi函数只返回一个内部重载函数。

有关TypeScript重载的详细信息,请参阅the documentation中的重载部分。