I am playing with union types in Typescript a I just realised that they can be used to express polymorphism instead of inheritance. Comming from Java I would write something like this.
interface Smiley {
print(): string;
}
class Happy implements Smiley {
print() {
return ':-)';
}
}
class Sad implements Smiley {
print() {
return ':-(';
}
}
On the other hand, I can express the same thing with unions
class Happy {
print() {
return ':-)';
}
}
class Sad {
print() {
return ':-(';
}
}
type Smiley = Happy | Sad;
What are theoretical or practical difference between these approaches?
One that comes to mind is that the first one allows the value of type Smiley to be anything that implements the Smiley interface. The second one only permits a Smiley to ever be Happy or Sad, nothing else.
Is there anything else that I am missing?