Playing around with recursive conditional types
In this article we will start playing with some of the new possibilities of recursive types, they are not yet in a stable version of TypeScript but will be expected in version 4.1 which will probably be released in november. We will finish with recursive types combined with tuple types
In previous versions of TypeScript there were already high order types. high order types are functions of types who have other types as arguments and can transform those to new types. But one of the resections was that you could not call your own type function by default without any trick. This was done to prevent you creating infinite loops in your types. The limitation of 50 type mapping deep is still existing.
Let start with an example, one of the util types TypeScript comes with is
ReadOnly. The definition is the following:
It maps every field in an object and makes them readonly. One this it does not. That is making the fields in the object
readonly. With the new recursive types we are able to make our own version of readOnly which recursively makes all the subtypes also
The difference between the default type and our own is that we check if it is an object type, if so then we call our own function type. See below for the difference in result:
Now we have recursion. We can solve a lot of type problems relatively easily. Another example is searching for all array types in an object and there are many more things possible than you can think of.
Arrays and tuples
Now we have recursion we can also loop through array types :). We still need an extra trick but don’t worry I will show you.
Here we have a type that search for the first occurance of a numeric type in an array by using recursion:
To get the tail we need to wrap it first in a function but after that we can continue with using recursion. With this principle we can implement a lot of array operations. For example geting the last item.
We hope to see this feature in production in half november. If you want to test it for yourself you can install the nightly build of TypeScript for more information see also the pull request on GitHub. Lets have fun and if you have more ideas with recursive types you can let us now in the comments.