gpt4 book ai didi

typescript - 在 Typescript 中,如何实现带重载的裸函数接口(interface)?

转载 作者:搜寻专家 更新时间:2023-10-30 21:10:30 26 4
gpt4 key购买 nike

我正在使用 Typescript 2.3.3

我正在尝试为我正在编写的一些代码创建一个不错的 API,因此我正在试验 Typescript 泛型的可能性。

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

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

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

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 规范的返回对象。

这可能吗?

最佳答案

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

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 中的重载部分.

关于typescript - 在 Typescript 中,如何实现带重载的裸函数接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45387232/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com