函数类型
函数可以指定参数的数据类型,也可以指定返回的数据类型, 如果指定的返回数据类型与返回的数据类型不匹配。
function add(x: number, y: number): number {return x + y;}let myAdd = function(x: number, y: number): number{return x + y;}
这两种写法很常见,当然还有没有返回值的情况
function add(x: string): viod {console.log(x);}
完整函数类型
let add: (x: number, y: number) => number =function(x: number, y:number): number{return x + y;}
通过上面函数,可以清晰的看出这个函数整体意思。
箭头函数
let add = (x: numebr, y: number) => x + y;
可选参数
有些情况下,在不确定传递几个参数的时候就需要特殊处理。
function buildName(firstName: string, lastName: string) {return firstName + " " + lastName;}let result1 = buildName("Bob"); // 错误的 缺少参数let result2 = buildName("Bob", "Adams", "Sr."); // 错误的 参数过多let result3 = buildName("Bob", "Adams"); // 正确// 正确处理function buildName(firstName: string, lastName?: string) {if (lastName)return firstName + " " + lastName;elsereturn firstName;}let result1 = buildName("Bob"); // 正确 可以执行let result2 = buildName("Bob", "Adams", "Sr."); // 错误的 参数过多let result3 = buildName("Bob", "Adams"); // 正确function buildName(firstName?: string, lastName?: string) {if (lastName)return firstName + " " + lastName;elsereturn firstName;}let result1 = buildName(); // 正确 可以执行
默认参数
function buildName(firstName: string, lastName="Bob") {return firstName + lastName;}let result1 = buildName("tom"); // "tomBob"let result2 = buildName("tom", "Pop"); // "tomPop"let result3 = buildName("tom", "Pop", "Adams"); // 错误的 参数过多
剩余参数
从上面可以看出如果定好了参数的数量,那么就最多只能这么多参数了。
function buildName(firstName: string, ...restOfName: string[]) {return firstName + " " + restOfName.join(" ");}let employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie");console.log(employeeName); // "Joseph Samuel Lucas MacKinzie"
重载
function attr(name:string):string;function attr(age:number):number;function attr(nameorage: any):any {if(nameorage && typeof nameorage === "string") {console.log('name');}else {console.log('age');}}attr("Tom"); // Tomattr(30); // 30
