Using Generics with Components 11 exercises

Wrapping a Generic Function Inside of Another

Here we have a function called useStateAsObject. The function is a simple wrapper for useState, but instead of returning a tuple, we're opting to return an object:

export const useStateAsObject = (initial: any) => {
const [value, set] = useState(initial);
return {

Loading exercise


00:00 In this exercise, we have a function called useStateAsObject, and we're just basically doing a simple wrapping of useState here. What we're doing is we're saying, instead of returning it as a tuple, I actually just want to return it as an object. Sometimes this is nice and this mimics

00:18 often what you want to do with certain things that wrap useState. Our example here really should be value like name mat and set React.dispatch any. But instead, it's being inferred as any. We should be having this name string being the example.value,

00:37 but instead, example.value is just typed as any. We need to figure out a way to make this function actually work. You notice that in this function call down there, we're not actually passing any type arguments. It seems that just from this usage here,

00:56 example is expected to understand that it's supposed to represent name string. Your job is to using some of the syntax that we've seen so far. In fact, you won't need that much here really, is to grab this and turn it into a generic function. There are many different solutions here,

01:13 but they all do involve instantiating a generic in some form. Good luck.