Issue
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?
Solution
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;
}
}
According to your type definition speak(wordsOrNum): string | number
wordsOrNum
might be a number
and return type might be a string
or vice versa
Answered By - captain-yossarian
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.