ts的函数类型

ts的函数类型

1、函数声明

function sum(x: number,y:number):number {
 return x+y;
}

注意:输入多余(或者少于要求的)参数。是不被允许的:

function sum(x:number,y:number):number {
  return x + y;
}
sum(1,2,3);//不被允许
function sum(x:number,y:number):number {
 return x + y;
}
sum(1);//不被允许

2、函数表达式

let mySum:(x:number,y:number) =>number = function(x:number,y:number):number {
  return x+y;
}

3、用接口定义函数的形状

interface SearchFun {
 (source:string,subString:string):boolean;
}
let mySearch: SearchFun;
mySearch = function(source:string,subString:string) {
 return source.search(subString) != -1;
}

4、可选参数

function buildName(firstName:string,lastName?:string) {
 if(lastName) {
 return firstName + '' + lastName
 } else {
  return firstName
 }
}
let tomcat = buildName('Tom','cat');
let tom = buildName('Tom')

需要注意的是:可选参数必须在必需参数后面,换句话说,可选参数后面不允许在出现必须参数了。

5、参数默认值

ts中会将添加了默认值的参数识别为可选参数,此时就不受【可选参数必须接在必需参数后面】的限制了

function buildName(firstName:string = 'Tom',lastName:string) {
 return firstName + '' + lastName;
}
let tomcat = buildName('Tom','Cat');
let cat = buildName(undefined,'Cat');

6、剩余参数

function push(array:any[],..items:any[]) {
  items.forEach(function(item) {
   array.push(item);
  })
}
let a = [];
push(a,1,2,3);

7、重载

function reverse(x:number):number;
function reverse(x:string):string;
function reverse(x:number | string):number | string | void {
 if(typeof x === 'number') {
  retrun Number(x.toString().split('').reverse().join(''))
 } else if(typeof x === 'string') {
  return x.split('').reverse().join('');
 }
}

你可能感兴趣的:(排序算法,算法,前端,typescript)