0

I have the following class which have overloading fucntion in typescript

export class Person {
      private get fullName() {
        return this.firstName + '' + this.lastname;
      }
      constructor(public firstName, public lastname) {

      }
      sayHi(): string;
      sayHi(name: string): string;
      sayHi(person: Person): string;
      sayHi(obj: any) {

     return '';
    }
    const name = new Person('jim', 'jonson');

when runing my app I get the following error :

Overload signature is not compatible with function implementation.

I change this line of code : sayHi(obj: any) to this line of code: sayHi() so now I have the following code

   export class Person {
          private get fullName() {
            return this.firstName + '' + this.lastname;
          }
          constructor(public firstName, public lastname) {

          }
          sayHi(): string;
          sayHi(name: string): string;
          sayHi(person: Person): string;
          sayHi() {

         return '';
        }
        const name = new Person('jim', 'jonson');

When I run the code above there is no errors.

Can some one please explain why there is no error on this code while we can see clear in the code above that there is Overload signatures that are not compatible with function implementation.? am I missing something or what? am confused

1 Answer 1

1

The last signature sayHi(obj: any) requires one argument, but your first overload specifies that you can call the method with no arguments. This is the incompatibility that typescript is pointing out.

To solve that, you can make the argument in that final signature optional, to indicate to typescript that you can call it without any arguments (thus making it compatible with your first overload):

sayHi(obj?: any)
Sign up to request clarification or add additional context in comments.

4 Comments

sayHi(obj?: any) to sayHi() also works my question is why? while we can see that its not compatibale, that is what I wanted to know, read again my question
@Kaczkapojebana , In anyway, whats the point of these overloads if the only way to use this method is without any params? It might work due to tslints or something, But you still cannot use your overloads, so I see no point with this example.
Now I get you ,
In your second example, those overloads are still compatible with the final signature. Basically, the final signature has to be assignable to the signatures of all the overloads, and since functions that take fewer parameters are assignable to those that take more, they are still compatible.

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.