Exploring union types in Typescript, I have discovered a new way to showcase polymorphism without relying on inheritance. In my previous Java background, I would typically approach it like this:
interface Emotion {
display(): string;
}
class Joy implements Emotion {
display() {
return '😄';
}
}
class Sorrow implements Emotion {
display() {
return '😢';
}
}
However, I have now realized that the same concept can be achieved using unions:
class Joy {
display() {
return '😄';
}
}
class Sorrow {
display() {
return '😢';
}
}
type Emotion = Joy | Sorrow;
What are the potential theoretical or practical distinctions between these two approaches?
One notable difference is that the first method allows any value of type Emotion to be any class that implements the Emotion interface. On the other hand, the second approach restricts Emotion to be only Joy or Sorrow instances.
Are there any other aspects that I might have overlooked?