1
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
  • Try to use wordsOrNum: unknown in the implementation Commented Feb 23, 2022 at 12:37

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

You are using generics. It seems like a good way. thank you.
const dog: Dog = { speak<T extends Dog>(wordsOrNum:T): T { return wordsOrNum; } }

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.