This project is read-only.

Function definition overloading (ambient vs. inline)

Topics: Language Specification
May 8, 2014 at 7:42 AM
There's a difference I noticed between the way I can specify function overloads inline vs. in an ambient declaration.

For instance, in a .d.ts:
module "foo" {
  function x(a: number): any;
  function x(a: string): any;
The above construction allows me to indicate that x may only be called with a number or a string. Nothing else may be passed.

However, I can't find a way to match this flexibility when writing definitions inline:
function x(a: number): any;
function x(a: string): any;
function x(a: any): any {

Because I need to write an implementation that uses types compatible with all overloads (the third case), I can't prevent callers from passing whatever they want in there.

I'm not sure if I'm just missing something, or if there is more flexibility on defining the function overloads in ambient declaration than in inline code.
May 8, 2014 at 12:31 PM
Scriby, actually the example you provided works exactly the way you want it - your function x has only two signatures (number and string). The implementation signature is not visible.

You can verify it yourself in Playground:

(CTRL+SPACE inside x())

For details see the last paragraph of Overloads chapter.
Note that the 'function pickCard(x): any' piece is not part of the overload list, so it only has two overloads: one that takes an object and one that takes a number. Calling 'pickCard' with any other parameter types would cause an error.