函数的类型注解
//使用function创建函数
function f(x:string,y:string):string{
return ""
}
//箭头函数
let fn:(x:string,y:string)=>string
fn=(a,b)=>a+b
//使用类型别名定义函数
type Add=(x:number,y:number)=>number
let add:Add=(x,y)=>x+y
//使用接口定义函数
interface Fn{
(x:string,y:string):string
}
let fnm:Fn =(x,y)=>x+y
函数的可选参数
type Add=(x:number,y:number)=>number
let add:Add=(x,y,z?:number)=>{
if(z){
return x+y+z
}else{
return x+y
}
}
可选参数使用?:进行修饰,必选参数不能位于可选参数之后
函数的剩余参数
type Add=(x:number,...rest:number[])=>number
let add:Add=(x,...rest)=>{
return x+rest.reduce((pre,cur)=>pre+cur)
}
在函数的参数不确定的情况下可以使用函数剩余参数
函数的重载
函数名相同参数类型和参数数量不同则实现重载
不需要为了相似功能的函数采用不同的函数名称
首先,定义一系列相同名称的函数声明,再实现函数,ts在重载的时候会查询定义列表,如果匹配则使用函数,如果不匹配则继续查找。
function add(...rest: number[]): number;
function add(...rest: string[]): string
function add(...rest: any[]): any {
let first = rest[0]
if (typeof first === "string") {
return rest.join(',')
}
if (typeof first === 'number') {
return rest.reduce((pre, cur) => pre + cur)
}
}