Solving Partial Autocompletion
The solution is to wrap string
in parentheses and intersect it with an empty object:
type LooseSize = Size | (string & {});
Confused? You're not alone. Even I don't understand why this works, but it is the solution to the problem at hand.
Let's break it down.
We have our `Siz
Transcript
00:00 You want to see the solution? The solution is to wrap this in parentheses, then take an and and intersect it with an empty object. What? How? Why would this possibly work? Well,
00:16 I have no idea why it works, but this is the accepted solution to this problem. What's going on here is that we have our size on one side and then by intersecting it with a string, it somehow computes it so that string no longer gets in the way of size. Because
00:31 if we remove this, you'll notice that actually this loose size is just inferred as string here. Whereas if you do this, then it computes it just enough so that it retains the other members of the union while still having this little section here kind of separated from
00:48 that. So by having this, it means that, okay, we're not going to compute the string just yet and that means it's just in time so that when the autocomplete comes in, the SM or XS is still available for the TypeScript server to show us. It's really strange. I think there
01:04 must be something happening in the compiler that's saying like eagerly compute this before we even show it to the people so that we get the autocomplete options and this prevents that. So this is the accepted solution. There is also, I think, in React itself, if we dive
01:19 into these types, if we take a look, there is a, and yeah, just here, which is in the ARIA role type at the top here. So for ARIA role, you can pass in alert, alert, dialogue, all this stuff and string and this. So it also accepts any string while giving us nice
01:36 autocomplete there. So this is a really, really, really strange quirk of TypeScript and certainly like TypeScript and prop types, but this is the accepted solution that's been adopted by the community and it's not going to break anytime soon because this has made its way
01:52 into actual code bases as you can see and the TypeScript team actually tests its version of TypeScript against every, almost everything in the community. It's a really smart testing system so this syntax is not going away, but I sort of wish they would make it kind of intrinsic or maybe a little bit prettier. So who knows, maybe sometime in the future
02:11 I'll be able to revisit this and actually change this out so that it's using the new
02:15 fancy syntax. But for now, this is the way to do it.