[TypeScript] Function Overloads in Typescript

It's common in Javascript for functions to accept different argument types and to also return different types. In this lesson we learn how to 'teach' Typescript about these dynamic functions so that we can still benefit from the powerful static type analysis.

复制代码
const getTasks = (taskname: string, x: any) : any => {
    if(typeof x === 'function'){
        return {taskname, fn: x};
    }

    if(Array.isArray(x)){
        return {taskname, deps: x};
    }
};

const task1 = getTasks('taskname1', ['dep1', 'dep2']);
const task2 = getTasks('taskname2', function(){});

task1.fn(); // Runtime Error, fn not exists on task1
task2.deps; // Runtime Error, deps not exists on task2
复制代码

 

In the code above, the IDE cannot help much during the compile time. 

But if we use Function overloads, then IDE can help to check error:

复制代码
interface GroupTask {
    taskname:string
    deps:string[]
}

interface Task {
    taskname:string
    fn:Function
}

function getTasks(taskname:string, x:string[]):GroupTask
function getTasks(taskname:string, x:Function):Task
function getTasks(taskname:string, x:any):any {
    if (typeof x === 'function') {
        return {taskname, fn: x};
    }

    if (Array.isArray(x)) {
        return {taskname, deps: x};
    }
}
const task1 = getTasks('taskname1', ['dep1', 'dep2']);
const task2 = getTasks('taskname2', function () {
});

task1.fn // Property 'fn' doesn't not exist on type 'GrouptTask'
task2.deps // Property 'deps' doesn't not exist on type 'Task'
复制代码

 

posted @   Zhentiw  阅读(244)  评论(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工具
点击右上角即可分享
微信分享提示