TypeScript函数类型

TypeScript函数类型

1.一般函数
function add(firstName : string,lastName : string, age : number) : string{
    return "FirstName: " + firstName + "    LastName: " + lastName + "  age: "+age;
}

add()                   //提供参数不匹配 error
add("zhang","san")      //提供参数不匹配 error
add("zhang","san",18)   //ok
2.有可选参数的函数
function add(firstName: string,lastName : string, age? : number) : string{
    if(age !== undefined){
        return "FirstName: " + firstName + "    LastName: " + lastName + "  age: "+age;
    }else {
        return "FirstName: " + firstName + "    LastName: " + lastName;
    }
}

add()                   //提供参数不匹配 error
add("zhang","san")      //ok
add("zhang","san",18)   //ok
3.有默认参数的函数
function add(firstName: string,lastName : string, age? : number) : string{

            return "FirstName:"+firstName+"LastName:"+lastName+"age: "+(age !== undefined ? age:0);

}
//为了提高代码可读性,于是做出如下修改
function add(firstName: string,lastName : string, age : number = 0) : string{

        return "FirstName: " + firstName + "    LastName: " + lastName + "  age: "+age;

}
4.带有可选参数的函数
function  add(...arr : number[]) : number{
    var result = 0 ;
    for (var i = 0 ; i < arr.length ; i++){
        result += arr[i];
    }
    return result;
}

add(1)      //result = 1
add(1,2)    //result = 3
add(1,2,3)  //result = 6 ......
5.函数重载
function add(name : string) : string;   //重载签名

function add(age : number) : string;    //重载签名

function add(flag : boolean) : string;  //重载签名

//实现签名
function add(value : (string | number | boolean)) : string{
    switch (typeof value){
        case "string" :
            return `my name is ${value}.`;    //这里的(`)是键盘esc键下面的那个(`)并非单引号
        case "number" :
            return `my age is ${value}.`;
        case "boolean" :
            return `i am ${value}`;
    }
}

console.log(add("jack")); 
console.log(add(18));
console.log(add(false));

你可能感兴趣的:(typeScript学习笔记)