This video is available to students only

Abstracting the type of data from server fetch

Although the custom server fetch() function we've established in the last lesson works, the data being returned isn't appropriately typed. In this lesson, we'll take advantage of TypeScript generics to ensure we get queried data from our server fetch() function with the appropriate type.

📝 This lesson's quiz can be found - here. 🗒️ Solutions for this lesson's quiz can be found - here.

Although our server.fetch() function works, we still have an issue where data retrieved from the server.fetch() function doesn't have a type associated with it.

To solve this, we'll take advantage of Typescript generics. We've seen how generics worked both in the Node server application as well the FunctionComponent type we initially surveyed, but we haven't had the chance to create our own generic abstraction.

We want the server.fetch() function to return the data from the request but we also want this data to be typed. We also want the fetch() function to work for any data object with its own unique type. The server.fetch() function has no idea what the type of data it returns could be. However, in the component where the fetch function is being called, we have an idea of the data we're expecting because we're defining the query we want to make.

For the listings query field, we expect an array of listings where id, title, image, address are to be strings and the price, numOfGuests, numOfBeds, numOfBaths, and rating fields are to be numbers.

If we have an idea of the shape of the data from the request, we essentially want to pass this shape of data into the server.fetch() function and we can achieve this with generics. First and foremost, in the server.fetch() function in the src/lib/api/server.ts file, we'll use angle brackets and declare that the function can accept a type variable denoted by TData.

We'll specify a default type parameter of any to say if the type of data isn't provided, we'll ensure the type is to be returned as any.

By having access to the TData type variable in our server.fetch() function, we can set the return type of the function to the type we expect. The res.json() function simply returns a value of Promise<any> and doesn't give us the option of passing in a type variable.

Start a new discussion. All notification go to the author.