zoukankan      html  css  js  c++  java
  • [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'
  • 相关阅读:
    TriSun PDF to X v11.0 Build 061
    资源管理器 Q-Dir v8.09
    USB启动盘创建工具 Rufus
    Docker:网络模式详解
    rsync使用实践
    MySQL 8.0 防止暴力破解
    MySQL-8.0.19 优化日志及压测
    MySQL入门篇之mysqldump参数说明
    rest-framework之视图
    rest-framework之权限组件
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5592632.html
Copyright © 2011-2022 走看看