1. 为函数定义类型
一般使用中,我们可以不必完整写出函数类型,因为 TypeScript 会为我们自动推断出类型,需要注意的是:类型中的参数名称可以不必和值中的参数名称匹配,只要它们类型是兼容的便可。
// 书写完成函数类型
let sum: (num1: number, num2: number) => number;
sum = function(num1, num2) {return num1 + num2
}
sum(1,2) // 3
2. 可选参数
参数名后面接一个 ?,该参数便成为了可选参数。注意:可选参数必须跟在必须参数后面
let square: (x: number, y: number, s?: number) => number;
square = function(width: number, height: number, scale?: number): number {if (scale) {return width * height * scale;} else {return width * height;}
};
square(5, 6); // 30
square(5, 6, 2); // 60
3. 默认参数
当用户没有给一个参数传递值或者传递的值是 undefined 时,这个参数叫做可以有默认值的参数,我们可以使用 = 指定这种情况下的取值,在所有的必须参数后面带默认值的参数都是可选的,与可选参数一样,在调用函数的时候是可以省略的,但是有默认值的参数不一定要放在必须参数的后面,也可以放在前面,当传入 undefined 的时候,就会取默认参数指定的默认值。
function square(width = 6, height = 6, scale: number, cut = 10): number {return width * height * scale - cut;
}
square(5, undefined, 2); // 5 * 6 * 2 - 10 = 50
4. 剩余参数
function max(a: number, b: number, ...resArr: number[]): number {return Math.max(a, b, ...resArr);
}
max(10, 5, 6, 100, 200); // 200