Adding Type Arguments to a Hook
Consider this useLocalStorage
function:
export const useLocalStorage = (prefix: string) => { return { get: (key: string) => { return JSON.parse(window.localStorage.getItem(prefix + key) || "null"); }, set: (key: string, value: any) => { window.localStorage.
Transcript
00:00 In this exercise, we're going to be doing something really interesting, which is using a or passing a type argument to a function. So useLocalStorage here, what we're doing is we're basically saying, okay, we've got a prefix, which is like a namespace that we're going to put all of this local storage entries under.
00:19 So here I have useLocalStorage name string user. So this is where I'm going to put all my users and their names, and it should let you get and set values. So it should let you say user.setMat name mat, except this mat user that's being returned is of type any. When we call user.getMat,
00:38 what we're expecting is for it to be name string or null. Because when you get something from local storage, you might not find it, and in which case local storage returns null. So it should also not let you set a value that is not the same type as the type argument passed in. So it should basically be erring here
00:56 because we're not passing in our name. There's an error here which is happening, expected zero type arguments but got one. That's because what we're trying to do here is pass in a type into useLocalStorage itself, like what we were doing with useState back in the previous modules.
01:15 So what your job is, is to try to find a way to make useLocalStorage a generic function, to turn it into something that takes in a type argument that we can manually pass in here. That's your job. So you will need to basically find some way to do that,
01:34 and then change the types of get and set so that it's not returning any here or not letting you pass in any, and the get here instead of returning any, actually returns the thing that we're receiving from this type argument.