The Utils Folder 10 exercises
solution

Make a Function Generic

As it currently stands, createStringMap is a non-generic function, meaning it's not designed to accept type arguments.

const createStringMap = () => {
  return new Map();
};

The first thing we'll do to make this function generic is to add a type parameter T:

const createStr
Loading solution

Transcript

00:00 Okay, currently, this function is just a function, not a generic function, it's a non-generic function. A generic function is one that can receive type arguments to it. So as we can see here, if we look inside here, we can see expected zero type arguments but got one.

00:17 Our createStringMap function is not expecting any type arguments. So let's give it a type parameter so it knows what to do when it receives a type argument. So here, we can say createStringMap, we're taking a T here, and this T can be anything, T, anything I want, but I'll just

00:32 call it T for now. Now, createStringMap takes in a T here, and this error has gone away. So now, we can see that it basically has this number locked in as its type argument, but it's still returning map, any, any. That's because we need to pass some type arguments

00:49 to map itself to basically tell it what to do here. So map, we know that the strings here, or rather the keys, are always going to be strings. So we can pass in a string as the first argument. And then in the second argument, you can see we get a nice little

01:05 pop-up here. We've got K, which is the keys, and V, which is the values. So now, we can pass in T because we have access to T in this scope. And now, this means that whatever we pass into this function, it then gets put into the map below it. Wonderful. So now,

01:23 for map, we end up with mapStringNumber. And when we pass an object here, we get mapStringObjectANumber. What we can do, if we don't pass in anything here, then we end up with mapStringUnknown. So by default, if you don't pass in a type argument, it's going to end up as unknown,

01:40 which is pretty nice. So this is the way that you can prepare a function to receive type arguments. And we've turned createStringMap from a normal function into a generic function.