I love typescript, it makes my life super easy and makes my dev experience far superior. That said one gripe I've always had in complex typescript codebase is with nested types, especially using things like
Omityou had to check the type definition, 4-5 levels deep to actually know what the type is, this can be quite annoying.
Recently I found a solution a great solution to this called Type Widening and it can be super easily implemented.
If you just want the basic type, here you go. That said I will break down how this works and how you can improve it below. You can also find a more advanced version of this with recursion and enum guards at bottom of the post.
Usage is very simple just wrap the type you want with
Widen<MyType>below is an embedded example which allows you to hover over the two types to see the difference
Enumquite a bit in our codebase and unfortunately there is no
T extends enumin typescript, so to hack around it you much create a Blacklist type which you can skip over
We can modify
ToPrimitiveto make it recursive like this
You can play with a demo below, which has all three different iterations setup for you
Not going into too much detail here, just a brief summary
This uses a combination of unity types from Typescript with conditional types to enable this
T extends stringchecks if the type is based on type string, which can be used as a conditional check. This allows us to check our base primitives like
To add support for functions, we need to check if the type has the structure of a function which we are doing by checking
T extends (...args: any) => anyThen we are returning the function with its correct parameters and return type using the
Feel free to email me any questions or suggestion on how I can improve this type or post at firstname.lastname@example.org