首页 > 其他 > 详细

ts中函数重载声明

时间:2021-04-07 12:25:58      阅读:17      评论:0      收藏:0      [点我收藏+]

函数的重载

//函数的名字相同,函数的参数和个数不同
    //需求:有一个add函数,他可以接受2个sting类型的参数进行拼接,也可以接受2个number类型的参数进行相加

    //函数重载声明
    function add(x:string,y:string) :string
    function add(x:number,y:number) :number

    function add(x:string|number,y:string|number) :string|number{
       if(typeof x ===‘string‘ && typeof y ===‘string‘){
           return x+y //字符串拼接
       }

       else if(typeof x ===‘number‘ && typeof y ===‘number‘){
         return x+y //数字相加
       }
    }

   console.log(add(1,2));
    
   console.log(add(‘11‘,‘22‘));

//    console.log(add(‘11‘,12)); 报错

技术分享图片

ts中函数重载声明

原文:https://www.cnblogs.com/malong1992/p/14626707.html

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