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?

1

1 Answer 1

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?");           
        }
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

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?
What do you mean? I get an error removing either overload.
See below for example.
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.
They indicate what you can call the function with. For example, you can't call bar.Foo({n: 3});
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.