[TypeScript] Function Overloads in Typescript

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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‘

 

以上是关于[TypeScript] Function Overloads in Typescript的主要内容,如果未能解决你的问题,请参考以下文章

[Typescript] Function defination

TypeScript 中的 function 和 => 有啥区别? [复制]

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

typescript-void-object-unknown-never-Function类型

Typescript 编译的 Javascript 代码不起作用(variable.default.function())

在 TypeScript 中为 Firebase Cloud Function 配置 mailgun