Using Generics with Components 11 exercises
Problem

Constraining a Type Helper to Accept Specific Values

Here we have the AllOrNothing and ToUndefinedObject type helpers from the previous exercise:


type AllOrNothing<T> = T | ToUndefinedObject<T>;
type ToUndefinedObject<T> = Partial<Record<keyof T, undefined>>;

However, there's a slight hiccup.

Currently, the type helpers are a

Loading exercise

Transcript

00:00 So we've introduced this new type helper into the code base. Everyone's happy, but there is a problem, which is we have like all or nothing can receive anything, like not just objects, like it can receive strings, numbers, undefined, null. Anything can be passed into this T here, which seems really, really strange.

00:19 So we want to find a way where we can warn people if they pass in something that's unsuitable. We only want to allow them to pass in objects into here. And while you're at it, we might as well do the same with two undefined object as well, because, you know, one without the other, it looks a little bit strange. So your job is to try to find a constraint

00:39 that we can add onto this T to make sure it only accepts certain types of values. And to also make sure that kind of the object is the thing that we want to be passed in here. This, there's no perfect solution to this, but really I just want you to get rid of a string or number or undefined from this. And I'll show you the limitations

00:58 of the few solutions that there are. Anyway, generic constraints, that's what you're looking for. Good luck.