Experiment: Quantified Types #2434
Open
+2,141
−172
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Imagine you have a function
consumeLayer...Okay good. How what if we need to consume two layers? We can have another parameter but then we'll also need another type parameter because the children of those two layers might be of different shapes. So it'd look like this...
Okay so far so good. Now what if we had to accept an array of layers? How do we dynamically create "n" generics? Surely one generic won't make the cut because each layer can have a different shape of children and having one generic will squash those child shapes into a union...
How do we solve this?
The answer is we can't. (Unless we employ some hacky workarounds that end up reducing type safety). But let's take a step back and think... Do we even need the generic on the function? Surely the layer type needs a type parameter to express it's structure but does that have to be on the function? What if TypeScript allowed us to express the structure like this...
If this was possible we could simply type the layers as
Layer[]and call it a day...This is precisely what this PR enables... You can create a type parameter out of thin air and have a richer way to express your types. Formally such types are called universally quantified types.
As a matter of fact this also unintentionally allows you to create "Self-Type-Checking" types... For example here's the
CaseInsensitivetype...Any self-type-checking type can be expressed as a quantified type, but not the other way round. And quantified types being superset of self-type-checking types is totally unintentional, I did not want to implement self-type-checking types again haha.
This
consumeLayersproblem is something I actually encountered while working at something else and I thought it would be fun to implement quantified types in typescript. So this PR is just an experiment and doesn't intend to be merged in (nor does it handle all edge cases). So feel free to close it. But I'd love to hear what thoughts y'all have on this. I'd also love to see what other use-cases people can come up with.Thanks for reading.