Passing Type Arguments 7 exercises
explainer

Passing Type Arguments in cal.com

The repo for cal.com has lots of great examples of how passing type arguments allows for overriding the weaknesses of external libraries.

For this example, we'll be looking at `Sendgrid

Loading explainer

Transcript

0:00 Here's an example of how the pattern of being able to pass type arguments to something is overriding the weaknesses of an external library. We're inside Cal.com, which again is a really amazing open-source application to look at if you want to look at some of these patterns.

0:16 We're inside a class called SendGrid. SendGrid itself is not generic, but it has a couple of generic functions inside here. The main one I'm looking at is SendGrid request. Now, if we look at some of the references here, what's going on is if we look in calendar service up here, what's going on is it's saying, "This .SendGrid.SendGrid request..."

0:40 Then it's passing in a type of argument that it's expecting to get back. This looks like just a new contact, a job ID. This result then is typed as SendGrid new contact. If we look inside here, this isn't actually used anywhere. It's just basically saying, "Promise are here," because we have client requests.

1:02 It looks like results here is basically typed as any. This is a really, really interesting use case where they've seen, "If we use this API as it is, we're going to get anys in our code base. Let's actually wrap it in something that does a little bit of error handling on the side, but also just make sure that the type we're getting back from the thing is what we expect it to be."

1:25 It basically makes the whole thing. It's not using Zod or something like this, which would actually make it run-time type-safe. It is giving an element of type safety and certainly documentable type safety. We know what it's supposed to return.

1:38 If it doesn't return, or something like that, or it returns something different, then there's something wrong and maybe we can introduce Zod at that point. This is a really, really interesting approach for working around something that's supposed to be there.

1:51 As you can see, this .SendGrid request is built out here in a few different ways and each one provides a different type definition which can be passed in.