function add(x:number,y:number):number{ return x+y; } let myAdd=function(x:number,y:number):number{ return x+y; } let myAdd1:(x:number,y:number)=>number=function(x:number,y:number):number{ return x+y; }
二、函数参数形式
(1)可选参数,参数名旁使用 ? ,可选参数必须跟在必须参数后面 。
function buildName(firstName: string, lastName?: string) { if (lastName) return firstName + " " + lastName; else return firstName; } let result1 = buildName("Bob"); // works correctly now let result2 = buildName("Bob", "Adams", "Sr."); // error, too many parameters let result3 = buildName("Bob", "Adams"); // ah, just right
(2) 默认参数,=,可以传入undefined值
function buildName1(firstName: string, lastName = "Smith") { return firstName + " " + lastName; } let result4 = buildName1("Bob"); // works correctly now, returns "Bob Smith" let result5 = buildName1("Bob", undefined); // still works, also returns "Bob Smith" let result6 = buildName1("Bob", "Adams", "Sr."); // error, too many parameters let result7 = buildName1("Bob", "Adams"); // ah, just right
(3)剩余参数
function buildName2(firstName: string, ...restOfName: string[]) { return firstName + " " + restOfName.join(" "); } let employeeName = buildName2("Joseph", "Samuel", "Lucas", "MacKinzie");
三、函数中的this,箭头函数
四、函数重载
参数不同,函数名相同