带 形参类型 和 函数返回类型 的函数
function add(x: number, y: number): number {
return x + y;
}
// 函数参数的定义 函数返回值的定义
let myadd = function (x: number, y: number): number { return x + y; }
函数的完整类型
let madd: (x: number, y: number) => number = function (x: number, y: number): number { return x + y };
编译器推断函数类型
//编译器推断类型
let numberAdd = function (x: number, y: number): number { return x + y };
//如果左边没有定义类型,右边定义了,编译器会推断出
let numberAdd2:(x:number,y:number)=>number=function(x,y){return x+y;}
//左边定义了,右边没有定义
固定参数
function build(firstname:string,lastname:string):string{
return firstname+" "+lastname
}
// let res1 = build("aa"); //报错只有一个参数
// let res2 = build("aa","bb","cc") //报错参数超过
let res3 =build("aa","bb");
可选参数 ?
//可选参数
function bu(firstname:string,lastname?:string):string{
return firstname+lastname;
}
let ress1 = bu("aa");
// let res2 = build("aa","bb","cc") //报错参数超过
let ress3 =bu("aa","bb");
默认参数
function strAdd(firstname:string,lastname:string="123"):string{
return firstname+lastname;
}
let re1 = strAdd("aa");
// let res2 = strAdd("aa","bb","cc") //报错参数超过
let re3 =strAdd("aa","bb");
剩余参数 不知道要传多少参数进来
//剩余参数 不知道会有多少参数传进来
function buildName(firstname:string,...arg:string[]):void{
console.log(firstname+""+arg.join())
}
let buildNameFun:(firstname:string,...arg:string[])=>void=buildName
重载
//函数重载
function getinfo(name:string):void;
function getinfo(age:number):void;
function getinfo(str:any):void{
if(typeof str=='string'){
console.log(str)
}else if(typeof str=="number"){
console.log("num"+str)
}
}