Union types

Intersection of available methods? I don’t see how that could work without structural typing (which I think is a bad idea, as discussed on other pages).

In the example above, while both First and Second have methods called speak(), they’re not the same method. (Unless both classes implement some interface defining speak() — but then you don’t need union types, as you can simply use that interface instead.)

Assuming two methods behave the same simply because they have the same name (and types) seems unwarranted, and potentially very dangerous. In an example like this where both classes are defined in the same project, you can mitigate the risk — but AIUI the main benefit of union types is to unify types you don’t have control over (else you could use an interface).

But apart from intersection of methods, what can you do with an instance of a union type? Apart from stuff common to every type (equality checks, string conversion, and storage), you’re reduced to type checks and smart casts just about everywhere you use them. I’m failing to see much benefit.

1 Like