Error when merging typescript interface function declaration(Merging Interfaces)

Viewed 47
interface Dog {
    speak(words: string): string;
}

interface Dog {
    speak(num: number): number;
}

const dog: Dog = {
    speak(wordsOrNum): string | number {
        return wordsOrNum;
    }
}

Interfaces are implemented as in the example code above, and declarations are merged.

However, when I try to implement a function in an object, an error occurs. Is this part possible?

enter image description here

1 Answers

In order to make it work you should assure TypeScript that input value is equal to return value:

interface Dog {
    speak(words: string): string;
}

interface Dog {
    speak(num: number): number;
}

const dog: Dog = {
    speak<Input extends string | number>(wordsOrNum: Input): Input {
        return wordsOrNum;
    }
}

Playground

According to your type definition speak(wordsOrNum): string | number wordsOrNum might be a number and return type might be a string or vice versa

Related