首页 > 其他 > 详细

[TypeScript] Function Overloads in Typescript

时间:2016-06-17 06:12:11      阅读:146      评论:0      收藏:0      [点我收藏+]

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‘

 

[TypeScript] Function Overloads in Typescript

原文:http://www.cnblogs.com/Answer1215/p/5592632.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!