Your interfaces define which members an object must have, but it doesn't define which members an object may not have. As a result, it is allowed for an IFish
to have a swim
method and vice versa.
Take a look at the updated example:
interface IFish {
swim: () => void;
meow: undefined;
}
interface ICat {
meow: () => void;
swim: undefined;
}
type Pet = IFish | ICat;
const pet: Pet = { // compilation error here
meow: () => {
//
},
swim: () => {
//
}
};
Here it is explicitly stated that an IFish must not define meow
, and an ICat must not define swim
. However, the problem with this approach is that if you have more than 2 interfaces and methods, you'll have to add a lot of these undefined
s to your type definitions.