函数类型

函数可以指定参数的数据类型,也可以指定返回的数据类型, 如果指定的返回数据类型与返回的数据类型不匹配。

  1. function add(x: number, y: number): number {
  2. return x + y;
  3. }
  4. let myAdd = function(x: number, y: number): number{
  5. return x + y;
  6. }

这两种写法很常见,当然还有没有返回值的情况

  1. function add(x: string): viod {
  2. console.log(x);
  3. }

完整函数类型

  1. let add: (x: number, y: number) => number =
  2. function(x: number, y:number): number{
  3. return x + y;
  4. }

通过上面函数,可以清晰的看出这个函数整体意思。

箭头函数

  1. let add = (x: numebr, y: number) => x + y;

可选参数

有些情况下,在不确定传递几个参数的时候就需要特殊处理。

  1. function buildName(firstName: string, lastName: string) {
  2. return firstName + " " + lastName;
  3. }
  4. let result1 = buildName("Bob"); // 错误的 缺少参数
  5. let result2 = buildName("Bob", "Adams", "Sr."); // 错误的 参数过多
  6. let result3 = buildName("Bob", "Adams"); // 正确
  7. // 正确处理
  8. function buildName(firstName: string, lastName?: string) {
  9. if (lastName)
  10. return firstName + " " + lastName;
  11. else
  12. return firstName;
  13. }
  14. let result1 = buildName("Bob"); // 正确 可以执行
  15. let result2 = buildName("Bob", "Adams", "Sr."); // 错误的 参数过多
  16. let result3 = buildName("Bob", "Adams"); // 正确
  17. function buildName(firstName?: string, lastName?: string) {
  18. if (lastName)
  19. return firstName + " " + lastName;
  20. else
  21. return firstName;
  22. }
  23. let result1 = buildName(); // 正确 可以执行

重点在这个?上,代表了不确定性。可以传,也可以不传。

默认参数

  1. function buildName(firstName: string, lastName="Bob") {
  2. return firstName + lastName;
  3. }
  4. let result1 = buildName("tom"); // "tomBob"
  5. let result2 = buildName("tom", "Pop"); // "tomPop"
  6. let result3 = buildName("tom", "Pop", "Adams"); // 错误的 参数过多

剩余参数

从上面可以看出如果定好了参数的数量,那么就最多只能这么多参数了。

  1. function buildName(firstName: string, ...restOfName: string[]) {
  2. return firstName + " " + restOfName.join(" ");
  3. }
  4. let employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie");
  5. console.log(employeeName); // "Joseph Samuel Lucas MacKinzie"

参数2它是数组的模式,所以参数的数据类型必须数组。

重载

  1. function attr(name:string):string;
  2. function attr(age:number):number;
  3. function attr(nameorage: any):any {
  4. if(nameorage && typeof nameorage === "string") {
  5. console.log('name');
  6. }else {
  7. console.log('age');
  8. }
  9. }
  10. attr("Tom"); // Tom
  11. attr(30); // 30