Consider the interface CommicBookCharacter
interface CommicBookCharacter {
name: string;
fight : (nemisis: CommicBookCharacter) => void;
}
Which may be implemented by both heros and villian. Besides of these characters, there are also civilians
class Civilian{
constructor(public name: string) {}
}
and here is how a hero could be implemented
class SuperHero implements CommicBookCharacter {
fight: (villian: Civilian) => void;
constructor(public name: string) {
this.fight = (hero)=> {
alert(this.name + ' is struggling back');
};
}
}
Lets create some characters as well
var spiderMan= new SuperHero('Spider Man');
var mj = new Civilian('Mary Jane');
Here is my problem. The civilian class does not implement the ComicBookCharacter interface, but the SuperHero can still implement the fight method with the Civilian argument.
This results in some bad problems:
spiderMan.fight(mj);
As a side note: if I would change the type of villian in the SuperHeru class to, say string, it would give me an compilation error. In my opinion, this is a buggy behavior. SpiderMan should not be able to fight Mary Jane!
fightexplicitly requires aCivilianinstancefight: (villian: Civilian) => void;If you had usedComicBookCharacteras the parameter type, it wouldn't compile successfully. If that's not the issue you mean, could you please provide a bit more detail about the problem?