[TypeScript] Overload a Function with TypeScript’s Overload Signatures

Some functions may have different return types depending on the types of the arguments with which they’re invoked. Using TypeScript’s function overloads, you can create an overload for each allowed combination of parameter and return types. This way, all type-correct signatures of a function are encoded in the type system and can be surfaced by the TypeScript Language Service within your editor.

 

复制代码
/**
 * Reverses the given string.
 * @param string The string to reverse.
 */
function reverse(string: string): string;

/**
 * Reverses the given array.
 * @param array The array to reverse.
 */
function reverse<T>(array: T[]): T[];

function reverse(stringOrArray: string | any[]) {
    return typeof stringOrArray === "string" 
    ? [...stringOrArray].reverse().join("") 
    : stringOrArray.slice().reverse();
}

// [ts] const reversedString: string 
const reversedString = reverse("TypeScript");
// [ts] const reversedArray: number[]
const reversedArray = reverse([4, 8, 15, 16, 23, 42]);
console.log(reversedString)
console.log(reversedArray)
复制代码

 

posted @   Zhentiw  阅读(416)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2017-09-14 [Vue + TS] Create your own Decorators in Vue with TypeScript
2017-09-14 [Vue + TS] Use Dependency Injection in Vue Using @Inject and @Provide Decorators with TypeScript
2017-09-14 [D3JS] Add more map layer and color
2017-09-14 [Javascript] Iterate Over Items with JavaScript's for-of Loop
2016-09-14 [Angular 2] More on *ngFor, @ContentChildren & QueryList<>
2016-09-14 [Angular 2] *ngFor
2016-09-14 [Angular 2] Directive intro and exportAs
点击右上角即可分享
微信分享提示