Designing Your Types 11 exercises
Problem

Add Constraints to a Type Parameter

We're back with the Result type, that accepts a TResult and TError with Error as the default:


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

We want to unify our error handling

Loading exercise

Transcript

00:00 We're back with our result type. We've got our tResult, tError equals Error, so we've still got our default in there. But we want to unify our error handling a little bit. And what we're going to assume now is that basically anything that you pass into this tError slot

00:17 should be at least an object with a required message on it. So if we look at this bad example here, it should be Erroring here because we're just passing in String. We've realized we just don't want to throw random Strings around. It's just not feeling great. So instead, we want to allow certain things. We want to allow a type Error.

00:36 Great, because that has a message property on it. And we want to allow custom ones, so with a message or String and a code number. And we want to allow just an object with a message on there. We shouldn't allow something with an optional message, for instance. But anything with a message is great by us.

00:52 Your job is to work out what syntax you need to use in this result to basically say, constrain this tError to be an object with a message property. And we still want to keep the default, but we need that constraint in there. I'll add a link below. Good luck.