Home > Software design >  This overload signature is not compatible with its implementation signature
This overload signature is not compatible with its implementation signature

Time:08-16

I have a function that accepts a number or a string, and, if the type is string returns 'string' or if the type is number it returns number.

Code:

function stringOr1(v: number): number;
function stringOr1(v: string): string;

function stringOr1(v: number | string) {
  if (typeof v == 'string') {
    return 'string';
  }
  else {
    return 1;
  }
}

const s1 = stringOr1('1');
const s2 = stringOr1(1);

TS error:

This overload signature is not compatible with its implementation signature.

What am I doing wrong?

CodePudding user response:

Just don't let the type inference do the typing for the returned type as it returns "string" | 1.

function stringOr1(v: number | string): number | string {
  if (typeof v == 'string') {
    return 'string';
  }
  else {
    return 1;
  }
}

The reason behind why the compiler is doing this is simple, you are not using any variables, so the compiler infers that the return type cannot be wider than "string" | 1.

CodePudding user response:

I wrote a sample code to use method overloading with interface & class find the sample below & try it out in typescript playground.

interface iStrOrI {
 stringOr1(v: number): number;
 stringOr1(v: string): string;
}

class StrOrI implements iStrOrI {
    stringOr1(v: number): number;
    stringOr1(v: string): string;
    stringOr1(v: number | string): string | number {
        if (typeof v == 'string') {
            return 'string';
        }
        else {
            return 1;
        }
    }
}

Run this code in typescript playground here: Playground url

when you are doing a method overloading, specifying explicit return types during implementation will not give you that error during transpile phase.

Useful information on method/function overloading https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads

  • Related