Designing Your Types 11 exercises
solution

Specify a Default Type Parameter

Similar to other times you set default values, the solution is to use an equals sign.

In this case, we'll add the = after the TError type parameter, and then specify Error as the default type:


type Result<TResult, TError = Error> =
| {
success: true;
data: TResult;

Loading solution

Transcript

00:00 The solution here is to say type result, T result, T error, and then after the T error to add an equal sign, and then say equals error. Beautiful. Now, type results here. Basically, if we add an example, so we say type example equals our result.

00:17 We still have to pass it some generic parameters, or some type arguments, and then we can say results, and let's just say string, for instance. Now, if we hover over example, we can see that data is a string. When success is true, an error is an error when it's false, and notice this doesn't constrain this at all.

00:35 We can still pass anything we want to into error. We can still pass in number, for instance, if that's the sort of thing that we want to be returning as the number slot, and there you go, so error is now number, but if we don't pass anything, now we can say, fantastic, it's error by default, and we can do this with all of the generic,

00:54 the type parameters if we want to. So we can say T result equals string, for instance, if we don't pass anything in, and now it will basically almost treat it like a non-generic type if you don't pass in any type arguments. Suddenly, we don't require any type arguments anymore. Fantastic.

01:12 So when the success is true, it's now defaulted to string and defaulted this branch to error, but this one, we don't want that. We don't want all of the elements to be default, and of course, just like in JavaScript, if you specify T result equals string, and then the other one is required, then it's going to yell at you because required type parameters

01:30 may not follow optional type parameters. So this is another tool in our toolbox, just basically making more helpful generic types that we can use throughout our code base. Lovely.