/** 为函数定义类型 */ // 为函数的参数指定类型,为函数的返回值指定类型 function add(x: number, y: number): number { return x + y; } let myAdd = function (x: number, y: number): number { return x + y; } // 完整的函数 let myAdd2: (x: number, y: number) => number = function (x: number, y: number): number{ return x + y } let myadd3: (x: number, y: number) => number = function (x: number, y: number) { return x + y } let myadd4: (b: number, y: number) => number = function (x: number, y: number) { return x + y; } let myadd5: (x:number, y: number) => number=function(x,y){return x+y} // 可选参数和默认参数:ts里传入一个函数的参数个数必须与函数期望的参数个数一致 function buildName(firstName: string, lastName: string) { return firstName + " " + lastName } let result = buildName("jsck", "bruce") let result1 = buildName("jsck") console.log(result1) // 可选参数必须放在后面 function buildName2(firstName: string, lastName?: string) { return firstName + " " + lastName } let result2 = buildName2("jsck", "bruce") let result3 = buildName2("jsck") console.log(result2) console.log(result3) // 默认参数,当用户没有传值或者传递的值是undefined的时候生效 function buildName3(firstName: string, lastName="smith") { return firstName + " " + lastName } let result4= buildName3("bob", undefined) // 剩余参数 function buildName4(firstName: string, ...restOfName: string[]) { return firstName + ',' + restOfName.join(",") } let employeeName = buildName4("xiaoju", "weimeng", "ruixin", "tengying") console.log(employeeName)