前言

需要知道,Javascript 是没有重载的,只能通过其他方式实现。但是 Typescript 是 javascript 的超集,赋予静态类型检测,加上了类型,其实就有了重载的可能。

什么是函数重载?

函数的命名一样,但是 参数类型参数个数、参数顺序` 不一样,称为函数重载
eg:

  1. function eat (food: string): shit;
  2. function eat (food: string, count: number): shit;
  3. function eat (food: string, count: string): shit;
  4. function eat (count: number, food: string): shit;

细节理解

  • 首先,认识一下函数的参数,函数声明时参数表面上只是 形参 ,可以理解为形式上的参数,供函数内部使用,实际的值是未知的。在调用时,传入实际的参数值,叫 实参 ,可理解为有实际值的参数,传入函数内部。
  • 因为是函数重载,实质上是形参数的变动,对于调用方,他们关注的是传参的类型,所以对于参数顺序不同这一点,其实是指不同类型的参数顺序不一样,如果两个参数类型一样,顺序的调整,在调用方角度是没有意义的。所以也不能称为重载。
  • 谈到意义,我们使用重载,意义在于拓展函数,让它具有多形态,根据不同场景满足使用不同形态。

tip:

  • 函数声明,它并不是重载的一部分: ```typescript function createLog(message: string): number; function createLog(source: string, message?: string): number { return 0; }

createLog(‘message’); // OK createLog(‘source’, ‘message’); // ERROR: Supplied parameters do not match any signature

  1. - 重载是ts意义上的重载
  2. ```typescript
  3. function createLog(message: string): number;
  4. function createLog(source: string, message: string): number;
  5. function createLog(source: string, message?: string): number {
  6. return 0;
  7. }
  8. createLog('message'); // OK
  9. createLog('source', 'message'); // OK