Designing Your Types 11 exercises
Problem

Default Type Parameters in Generics

Here we have the Result type that will either give us a success or an error:


type Result<TResult, TError> =
| {
success: true;
data: TResult;
}
| {
success: false;
error: TError;
};

We also have the createRandomNumber function, but this time it only spec

Loading exercise

Transcript

00:00 In this exercise, we're back with our result type here that has two results and two error on it and we're inside our createRandomNumber function. And we're returning a type now that's slightly different from the way it was in the previous exercise. In the previous exercise, we were passing result, error.

00:17 And we were saying, OK, the first argument is going to be the result if it's successful. Otherwise, it's going to be the error if it's not successful. But it's kind of getting a bit of a pain in the bum to always specify error here. Because, sure, sometimes it's like syntax error, sometimes it's a more interesting type of error.

00:34 But it would be really great if we could specify a default so we didn't have to specify that it returns an error. So, your job is to try to figure out how we can change this type of result to make sure that tError defaults to the error type. So, if we look at this, there is actually an error type.

00:52 So, you can say type example equals error like this. And this is basically the type of a standard error because the class is available globally and the interface is available globally. So, your job is to work out what syntax you can use to make sure that tError defaults to error.