Create a Typescript Union Type from a Javascript Object

Learn how to create a union type from a javascript object that automatically updates itself using advanced Typescript techniques like Mapped Types

Share with a coworker

Social Share Links

Send Tweet

Transcript

[00:00] For this new TypeScript tip, let's learn how to derive a type like the following this union from an object like this the first step to do that is to bring the user object here from the value world into the type world. To do that, let's create a new type and use the typeof keyword into the user object. That will create this kind of type. Now, we will use an advanced technique on TypeScript named MappedTypes to create a new type based on this type. And to do that, we create a new object.

[00:48] And let's use this funky syntax key in key off. We just use the key off keyword type from user. And let's create, let's say that this is an object. This is kind of a for loop in the JavaScript world or any other language, but it will loop through the keys of type from user. Let's see what are those keys type keys key of type from user.

[01:25] So is that name, age and email. And then we'll set all of that inside this new type. Now we need to pass this thing inside here. And to do that, we can iterate again or map again. Key two in key.

[01:49] And let's say that that will be type from user key two. Now our map type looks like that, but we still have these duplicated things here. Right. So we can get rid of that by using the keyof type from user. And now we have the union type that we wanted.

[02:16] Why is this so useful? Because since we are deriving this from the user object, any change I do to the user object, like adding a new attribute here, will be immediately represented into the MAP type or this union type. If you want to learn more about these important and very useful keywords like typeof and keyof, you can go to the Ege block and read the learn the key concept of TypeScript powerful genetics and map types. Here you will find more information about each of these operators.