Designing Your Types 11 exercises
Problem

Introduction to Generic Types

Consider the types UserDataShape and PostDataShape:


type ErrorShape = {
error: {
message: string;
};
};
type UserDataShape =
| {
data: {
id: string;
name: string;
email: string;
};
}
| ErrorShape;
type PostDataShape =
| {
dat

Loading exercise

Transcript

00:00 In this exercise, we're going to be tidying up some code, reducing some duplication. We have a user data shape here, and we have a post data shape below. You notice the similarities between both of these. They each have a data object, and then they also have an error shape as the other member of the union.

00:18 The error shape is just up here, error message string. And the data between them is slightly different. So they both have an ID property, but they have ID title and body on the post, and ID name and email on the user. Your job is to work out how we can reduce the duplication between these two here.

00:37 So user data shape, like whatever data shape we seem to have in this application, it's like it always comes back in like a data or error object. And then the consumer of this imaginary API needs to figure out whether it's got some data or it's an error. So we want to create basically a data shape type helper.

00:57 And this data shape type helper is basically going to look like this. I'm just going to say like type user data shape equals data shape, and then we can pass it the actual entity that we have here. So if I just uncomment this, this will probably be easier. So like that, you can now see what I'm trying to get at here.

01:15 So user data shape will look like this, and a post data shape, you'll just be able to pass the post in and it should just work. Your job is to try to figure out how we create a data shape type helper here or generic type. And I'm going to link below to the docs that will help you do that. Good luck.