4 ms·
> Finally, be aware that for a conditional type to trigger distributivity, the checked generic must be by itself to the left of extends, that is, not passed int
by steve_adams_86 5y ago
> Finally, be aware that for a conditional type to trigger distributivity, the checked generic must be by itself to the left of extends, that is, not passed into another generic or otherwise altered during the check.
Ah, this helped my brain click with a problem I’ve encountered several times. I think the most common reason I encounter this is when using generic memoized components in React. The generic parameters seem to be missed by the compiler completely, so something like a memoized polymorphic component becomes impossible to compose further into other components.
I guess the problem is that the memo function has inferred generic parameters which causes distributivity to be disabled on the nested generic parameters.
At least I think this is the case. I need to dig a little deeper, but I’m fairly sure this explains it.
This was a great read. I intuitively think in sets quite often, but it hadn’t occurred to me how overt the set theory is in TypeScript. This opened my eyes to the reason behind certain unintuitive behaviours (especially intersecting interfaces).
- brundolf 5y agoAs an aside, a workaround for that case is: const Comp = React.memo(NonMemoComp) as typeof NonMemoComp
- steve_adams_86 5y agoYeah, this has been the approach I’ve used but the purist in me really goes crazy not having it “just work”. Admittedly it’s pretty hard to have casting in cases like this come back to bite you. I suppose you could even write a lint to ensure memoized component casting is correct.