Beginner's TypeScript Tutorial (18 exercises)
solution

Two Techniques for Creating New Types Based on Others

There are a couple of solutions here that both make use of TypeScript's built-in helpers.

Use Omit

The first solution is to Omit.

According to TypeScript, this constructs a type with the properties of T except for those in type K.

Here's what the syntax looks like:

type MyType = Omit<User, "id">;

What we're saying here is create a type with everything that User has except for id.

Use Pick

The second solution is to use Pick, which is the inverse of Omit:

type MyType = Pick<User, "firstName" | "lastName">;

Here we're taking User and picking its firstName and lastName properties.

Note that Pick provides autocompletion while Omit does not.

This is because you are able to omit keys that aren't present on the original type, which means you end up with all of its properties. This is an advanced problem that we will tackle down the road.

For now, just know that both of Omit and Pick are globally available in TypeScript and are extremely useful tools.

Transcript

We've got two solutions here. Both of them use type helps from TypeScript's built-in selection. Here, we've got a type helper which is saying Omit. What an Omit is doing is constructing a type with the properties of T, except for those in type K. What on earth does that mean?

What it means is that we're creating a new type without ID in here. If we want to, we could omit firstName and we'd end up with just ID and lastName. We could even omit either firstName or lastName here, and we'd end up with just the ID. That's the first method of doing this. You don't need to import from anywhere. This is a globally available type in TypeScript, and it's extremely useful.

The second one is we've got the inverse of Omit, which is Pick here. Pick, just like Omit, constructs a set of properties, except it's the inverse. It just picks the ones you want. If we wanted to only pick the ID type, then we would get that here. If we wanted to just pick firstName or just pick lastName, then we'd end up with the whole thing.

You might be wondering why you get autocompletes on this one instead of on this one. That's something normal to notice. What you might see is that you can omit keys that aren't there, and you just end up with the whole thing. This is an advanced problem, so we will tackle this down the road. I promise.