When using interfaces, you are specifying the members that an object must have, but not restricting which members it cannot have. This means that an IFish
can have a swim
method and vice versa.
Let's examine a revised example:
interface IFish {
swim: () => void;
meow: undefined;
}
interface ICat {
meow: () => void;
swim: undefined;
}
type Pet = IFish | ICat;
const pet: Pet = { // error in compilation
meow: () => {
//
},
swim: () => {
//
}
};
In this demonstration, we explicitly declare that an IFish should not have a meow
method, while an ICat should not have a swim
method. The downside to this approach is that managing multiple interfaces and methods may require adding numerous instances of undefined
to your type definitions.