ts中函数重载声明


函数的重载

//函数的名字相同,函数的参数和个数不同
    //需求:有一个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)); 报错


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM