The Unconstrained Maybe Type Helper
The first step to turning the
Maybe type into a type helper is to add angle brackets and an argument of
T which will also be the return value for now:
type Maybe<T> = T
To help us check our work, we'll create an
Example type that equals
Maybe and give it a
0:00 The solution here is to take these Maybe type. We're going to first need to change it into a TypeHelper. We're going to give it some angle brackets and a T. This makes the first argument of our type function here, TypeHelper.
0:14 Let's return T for now. We'll say, type Example = Maybe and let's give it a string. This is very similar to the solution from our previous exercise and we know then that this is going to return a string.
0:26 The way that we make changes to this return type here is we're going to say, T or null. Now, we get a string or null here. If we add in undefined here too, then suddenly, everything starts passing, because we've got string or null or undefined. Pass in a number, get the same thing.
0:44 This is not constraint at all by the way. We can pass in things like unknown, we can pass in things like any, as well. Any destroys this whole union here. We can even pass in a null itself and null will get collapsed, because if there's two unions at the same type or two union members of the same type, and they get squashed together.
1:05 This is pretty cool. This gives us the ability to have a Maybe type here that we can put in to all places, if we need it. I've certainly, find cases where I need lots of different Maybe types and I've seen this used in libraries before.