Distributing match types over unions

The docs for match types call out that they differ from TypeScript’s conditional types in that they do not distribute over unions. They previously mentioned that supporting this should be investigated.

Did that investigation happen? I’d be curious to know the results!

Without this feature, it feels like there should perhaps be some way to explicitly iterate over the member types of a union. Has there been prior discussion on something like that?

Hey, I do not believe that this has been discussed at all recently - For it to work there would probably have to be a normalisation step that removes duplicates. However that’s not the whole story:

match types rely on distinguishing cases by runtime semantics - e.g. that it can only fall through to the next case if it can prove that the types can be distinguished by a runtime check. since union types are not discriminated, (e.g. A | A can not be distinguished with a runtime check) proving that each part is distinct is not simple at all.

1 Like

I forgot to say that you can use macros to pattern match on types, which could let you iterate over all branches of a union type, but macro calls can only occur through method calls right now, so some flexibility is lost.

I think the idea would be to define that

(A | B) match <cases>  =:=  (A match <cases>) | (B match <cases>)

At first glance this looks plausible. But we’d need to take a close look at whether this is sound (Typescript’s precedence does not help, since soundness is not a guarantee with Typescript).

The other question is whether there are convincing use cases that would require this change.

1 Like