3、Typescript 函数

ts中函数:

  • 1、函数返回值定义:
    • 1-1、function fun1():string{}
    • 1-2、let fun = function():number{}
  • 2、函数参数类型定义:
    • 2-1、function fun1(name:string, age:number):string{}
    • 2-2、let fun = function(age:number):string {}
  • 3、 函数参数可选(参数后跟着?号表示可选)
    • 3-1、function fun1(name:string, age?:number):any{}
  • 4、函数的默认参数
    • 4-1、function fun1(name:string, age:number = 10):any{}
  • 5、函数的可变参数
    • 5-1、function fun1(age:number, ...num:number[]):number{}
  • 6、函数的重载
    • 6-1、根据类型判断
function fun1(name:string):string;
function fun1(age:number):string;
function fun1(str:any):any{
   if(typeof str === 'string'){
      return 'string == ' + str;
   }else {
       return 'number == ' + str;
   }
}
  • 6-2、根据参数判断
function fun1(name:string):string;
function fun1(name:string, age:number):string;
function fun1(str:string, age?:number):any{
  if(age){
    return 'string == ' + str+ ', age === '+ age;
  }else {
    return 'number == ' + str;
  }
 }

案例:

// 1、ts函数返回类型定义
function fun1():string {
    // 不能将类型“122”分配给类型“string”。ts(2322)
    // return 122;

    // 返回字符串
    return '123字符串';
}
console.log('fun1 == ', fun1());

// 2、ts匿名函数返回类型定义
let fun2 = function():number {
    return 123345
}
console.log('fun2 == ', fun2());

// 3、ts中函数参数类型定义
function fun3(name:string, age:number):string{
    return `name == ${name},age == ${age}`;
}
console.log('fun3 == ', fun3('zs', 20));

// 3、ts中匿名函数参数类型定义
let fun4 = function(age: number):number{
    return age
}
console.log('fun4 == ', fun4(123));

// 4、ts中方法可选参数,参数后跟着?号
let fun5 = function(name:string, age?:number):any{
    return 'abcdefg';
}
console.log('fun5 == ', fun5('233'));

// 5、ts中函数参数默认值
function fun6(name: string, age: number = 10):any{
    console.log(`name == ${name}, age == ${age}`);
}

fun6('zs')

// 6、ts可变参数
function fun7(age:number, ...num:number[]):number {
    let sum = age;
    for(let i=0;i

你可能感兴趣的:(3、Typescript 函数)