4

Anders give this example of an interface overload, but I don't get how it would be implemented and used:

interface Fooable
{
   Foo(n:number) : string;
   Foo(s:string) : string;
}

Can someone give me an example of implementing and using this?

Greg Gum
  • 33,478
  • 39
  • 162
  • 233
  • Possible duplicate of [Functions Overloading in interface and classes - how to?](http://stackoverflow.com/questions/13219289/functions-overloading-in-interface-and-classes-how-to) – Louis Mar 06 '17 at 21:08

1 Answers1

4
class Bar implements Fooable {
    Foo(n: number): string; 
    Foo(n: string): string; 
    Foo(n: any) {
        if(typeof n === 'number') {
            return n + ' is a number';
        } else if(typeof n === 'string') {
            return n + ' is a string';
        } else {
            throw new Error("Oops, null/undefined?");           
        }
    }
}
Ryan Cavanaugh
  • 209,514
  • 56
  • 272
  • 235
  • Thanks very much. In testing this, it seems `Foo(n: number): string;` isn't actually required in the class (it compiles without error without it.) What is the purpose of that line? – Greg Gum Feb 18 '14 at 19:56
  • What do you mean? I get an error removing either overload. – Ryan Cavanaugh Feb 18 '14 at 20:01
  • See below for example. – Greg Gum Feb 18 '14 at 20:06
  • 1
    Removing two lines is different than removing one line! You can satisfy the interface by providing a function that is a subtype of the required function. In other words, a function that can take _anything_ and returns a string is an acceptable substitute for a function that can take a number or a string and return a string. – Ryan Cavanaugh Feb 18 '14 at 20:11
  • OK, great, I get it now. But what are those lines doing? They get compiled away - I really don't see a purpose for them as they are not actually implementing anything, yet they are in the class. (Just trying to fully understand what is going on.) – Greg Gum Feb 18 '14 at 20:16
  • 1
    They indicate what you can call the function with. For example, you can't call bar.Foo({n: 3}); – Ryan Cavanaugh Feb 18 '14 at 20:23
  • How to do it inline? – Pengő Dzsó Nov 02 '16 at 14:32