Derive a union type from an object

Learn how to derive a union type from an object - an incredibly useful switcheroo that's at the heart of most TS magic out there.

Discuss on Twitter

Transcript

Hello, folks. For this TypeScript tip, I'm going to show you how to change this fruitCounts object here into a union type. Imagine our code is a little bit crap at the moment because, really, we want to be deriving this type, this union of objects, from this object. I'm going to show you how to do it.

What we're going to do is we're going to name this NewSingleFruitCount, and I'm going to create a new type here, which is type NewSingleFruitCount. This is going to be an object. This is going to get a little bit funky here. First of all, I'm going to make a type out of this const up here, which is going to be type FruitCounts equals typeof fruitCounts.

Inside here, I'm going to go K in keyof FruitCounts is going to be...Let's, first of all, make it an object. This is going to be interesting because now, what we're going to have is fruitCounts is expecting this shape, where apple is now an empty object. In fact, it's even asking for apple is apple, which is an empty object or something crazy.

Essentially, what we have now is -- This is correct -- we're now looking for a shape like this. Inside, here we can specify anything and it will get put into here. We can say wow true, for instance, and now, all of these will require wow true. We don't want that. We actually want to take this key and we want to represent it as this apple number.

We're going to say K2 in K is a number. Now, each of these now require apple as a number. This is going to be 12, for instance, whatever. This is still not quite what we wanted. Even though we have all of this stuff represented, we've got this nice dynamic key here, it's still not quite a union.

To turn it into a union, all we need to do is map over these keys and essentially get rid of them. What we're going to do is just call these and say keyof FruitCounts. Maybe call isn't the right there. Now, what we have is we can have apple 2, and it satisfies it. There you go. This is how you turn a object type into a union.

More Tips