Narrowing in an Identity Function for Better Inference
The solution here is to take F.Narrow
from the ts-toolbelt
library and use it to wrap the little type parameter:
Now when this function is called with a tuple of elements, it infers the entire tuple of elements.
Transcript
0:00 The solution here is to take F.Narrow and use it to wrap this little type parameter here. We have F from ts-toolbelt. Now suddenly this function that when it's called with this tuple of elements, it infers the entire tuple of elements now. We have name, apple, name, banana and this is then inferred as its literal.
0:25 This is such a cool little piece of kit and I'm going to show you different use cases for it as we go. What I will say though, is if you're using TypeScript 5., which as of this recording isn't out yet, there will be an alternative to this, where you can use const T. const T will basically do the same thing as F.Narrow does.
0:46 I don't have TypeScript 5.. In fact, the beta isn't even released yet, so I can't show you it here, but this will be the syntax when you're looking at this from the future. ts-toolbelt's F.Narrow and this const T, nearly but pretty much basically reach the same conclusion, which is you end up with this deep narrowing happening at the generic level.
1:10 Without this, it would just be an array of name price. With it, you get F.Narrow and you get beautiful inference of the exact members of the tuple.