Reputation: 83
Here is my problem:
I have a class which implements interface. Method greet should have return type void
but in my implemented class it has string
and compiler doesn't warn me. And IDE neither (I'm using PhpStorm).
Am I missing something or is this intentional?
interface Person {
sex: string;
greet() : void;
}
class Boy implements Person {
sex: 'M';
greet() {
return this.sex;
}
}
I'm using Typescript 2.0.10
Upvotes: 1
Views: 371
Reputation: 164139
It won't complain because it doesn't really matter.
Your interface declares that the method returns void
, if your implementation returns a value then no harm will happen.
Example:
let person: Person = new Boy();
person.greet();
As person
is of type Person
(and not Boy
) then the greet
method won't return a value, and indeed I'm not trying to use a return value.
On the other hand if it was the opposite:
interface Person {
sex: string;
greet(): string;
}
class Boy implements Person {
sex: 'M';
greet(): void {}
}
Then an error is thrown:
Class 'Boy' incorrectly implements interface 'Person'.
Types of property 'greet' are incompatible.
Type '() => void' is not assignable to type '() => string'.
Type 'void' is not assignable to type 'string'.
Upvotes: 2