函数一般也会标识类型,主要是函数参数,函数返回值

  1. type Sum = (a: string, b: string) => string
  2. let sum: Sum = function (a: string, b: string): string {
  3. return a + b;
  4. }
  5. // 函数中默认参数,可选参数,剩余运算符
  6. let sum: Sum = function (a: string = 'a', b?: string, ...args: string[]) {
  7. return a;
  8. }

声明函数类型中 this 类型

  1. interface Worker {
  2. name: string
  3. }
  4. function working (this: Worker, time: number): string {
  5. return `${this.name} 已工作了 ${time} 小时`
  6. }
  7. working.call({ name: 'alex' } as Worker, 6)

声明了 this 类型之后就不能在不指定 this 的情况下调用了,因为不指定 this 时 this 类型为 void,跟 Worker 不一致

函数重载

  1. function sum(a: number, b: number): number
  2. function sum(a: string, b: string): string
  3. function sum(a: string, b: number): string
  4. function sum(a: number, b: string): string
  5. function sum(a: string | number, b: string | number): string | number {
  6. if (typeof a === 'string' && typeof b === 'string') {
  7. return a + b;
  8. }
  9. if (typeof a === 'string' && typeof b === 'number') {
  10. return a + b;
  11. }
  12. if (typeof a === 'number' && typeof b === 'number') {
  13. return a + b;
  14. }
  15. if (typeof a === 'number' && typeof b === 'string') {
  16. return a + b;
  17. }
  18. return ''
  19. }
  20. sum(1, 2);
  21. sum('1', '2');
  22. sum('1', 2);
  23. sum(2, '1');

函数类型声明