03_TypeScript function

1, the definition of the function

  The method defined functions es5

// function declaration process 
function RUN () {
     return 'RUN' ; 
} 
// function expression 
var RUN = function () {
     return 'RUN2' ; 
}

  The method defined function ts

// function declaration process (return value String) 
function RUN (): String {
     return 'RUN' ; 
} 
// function expression (return value numbet) 
var RUN = function (): Number {
     return 123 ; 
} 
// no return value of the method 
function RUN (): void { 
    the console.log ( 'RUN' ) 
}

   The method defined ts pass arguments (parameter data types need to be defined)

// function declaration process 
function getInfo (name: String, Age: Number): String {
         return `$ {name} --- $` {Age}; 
} 
// function expression 
var getInfo = function (name: String, Age : Number): String {
     return `$ {name} --- $` {Age}; 
}

 

2, optional parameter

// After the optional parameters plus a question mark, optional parameters must be configured to face the final parameters of the 
function getInfo (name: String, Age? : Number The): String {
     IF (Age) {
         return `$ {name} --- $ { } `Age; 
    } the else {
         return ` `$ {name}; 
    } 
} 
// Age this parameter can not pass pass 
getInfo ( 'zhangsan' ) 
getInfo ( 'zhangsan', 123)

 

3, the default parameters 

function run(name:string,age:number=20):string{
    return `${name}---${age}`;
}

 

 4, the remaining parameters (...)

function sum(...result:number[]):number{
    var sum = 0;
    for(var i=0;i<result.length;i++){
        sum+=result[i];
    }
    return sum;
}
alert(sum(1,2,3,4))

 

5, function overloading

java method overloading: overload refers to two or more than two a function of the same name, but their parameters are not the same, this time the situation will be overloaded.

Overloading typescript: providing a plurality of functions by a function of the type defined at a plurality of functions to test purposes.

function getInfo(name:string):string;
function getInfo(age:number):number;
function getInfo(str:any):any{
    if(typeof str==='string'){
        return '我叫:'+ str
    }else{
        return '年龄:'+ str
    }
}
getInfo('张三')
getInfo(20)

 

Guess you like

Origin www.cnblogs.com/MaShuai666/p/12354123.html