6.2 Function Overloads

Function overloads allow a more accurate specification of the patterns of invocation supported by a function than is possible with a single signature. The compile-time processing of a call to an overloaded function chooses the best candidate overload for the particular arguments and the return type of that overload becomes the result type the function call expression. Thus, using overloads it is possible to statically describe the manner in which a function’s return type varies based on its arguments. Overload resolution in function calls is described further in section 4.15.

Function overloads are purely a compile-time construct. They have no impact on the emitted JavaScript and thus no run-time cost.

The parameter list of a function overload cannot specify default values for parameters. In other words, an overload may use only the ? form when specifying optional parameters.

The following is an example of a function with overloads.

  1. function attr(name: string): string;
  2. function attr(name: string, value: string): Accessor;
  3. function attr(map: any): Accessor;
  4. function attr(nameOrMap: any, value?: string): any {
  5. if (nameOrMap && typeof nameOrMap === "string") {
  6. // handle string case
  7. }
  8. else {
  9. // handle map case
  10. }
  11. }

Note that each overload and the final implementation specify the same identifier. The type of the local variable ‘attr’ introduced by this declaration is

  1. var attr: {
  2. (name: string): string;
  3. (name: string, value: string): Accessor;
  4. (map: any): Accessor;
  5. };

Note that the signature of the actual function implementation is not included in the type.