Beginner's TypeScript Section 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 M
Loading solution

Transcript

0:00 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?

0:18 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.

0:45 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.

1:13 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.