//1、定义函数方法
function runs():string{
return 'abc'
}
//匿名函数
var fun2=function():number{
return 123
}
console.log(fun2) //123
//2、定义方法传参
function getMsg(name:string,age:number):string{
return `${name}---${age}`
}
console.log(getMsg('kk',18))
//方法可选参数
function getMsg2(name:string,age?:number):string {
return age?`${name}---${age}` : `${name}年龄保密`
}
console.log(getMsg2('kk',18))
console.log(getMsg2('yy'))
//tips:可选参数必须是最后一个哦
//默认参数
function getMsg3(name:string,age:number=20):string {
return `${name}---${age}`
}
console.log(getMsg3('GG'))
console.log(getMsg3('hello',60))
//剩余参数
function getSum(...result:number[]):number {
var sum=0;
for(var i=0;i<result.length;i++) {
sum+=result[i]
}
return sum
}
console.log(getSum(1,2,3))
function getSum2(a:number,...result:number[]):number {
var sum=a;
for(var i=0;i<result.length;i++) {
sum+=result[i]
}
return sum
}
console.log(getSum2(1,2,3)) //a就是1
//3、函数重载
//通过为同一个函数提供多个函数类型定义来实现多种功能的目的
//es5中同名方法会替换
//ts会重载
function getInfo(name:string):string;
function getInfo(age:number):number;
function getInfo(str:any):any{
return typeof(str) === 'string' ? `名字${str}` : `年龄${str}`
}
console.log(getInfo('张胜男'),getInfo(40))
// console.log(getInfo(true)) //错误写法