[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 a
, b
, or c
, the function should return a
, b
, 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'>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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