DEV Community

nukeop
nukeop

Posted on

Unleashing the Power of Typescript's Mapped Types

As developers, we all love the power and flexibility that Typescript brings to our code. But did you know that Typescript's mapped types allow you to create dynamic types that change based on the values of your variables? In this post, I'm going to dive into this lesser-known Typescript feature and show you how it can help you write even more powerful and flexible code.

Mapped types allow you to create new types by transforming properties of an existing type. In essence, they're like a map function, but for types. For example, say you have an interface like this:

interface MyInterface {
  foo: string;
  bar: number;
  baz: boolean;
}
Enter fullscreen mode Exit fullscreen mode

You can use a mapped type to create a new type that transforms all the property types to string:

type MyStringInterface = {
  [K in keyof MyInterface]: string;
}
Enter fullscreen mode Exit fullscreen mode

This creates a new type called MyStringInterface that has the same properties as MyInterface, but with all the property types set to string. So if you have a variable of type MyInterface, you can assign it to a variable of type MyStringInterface:

const myInterface: MyInterface = {
  foo: "hello",
  bar: 42,
  baz: true
};

const myStringInterface: MyStringInterface = myInterface;
Enter fullscreen mode Exit fullscreen mode

This is a powerful feature that can save you a lot of time and effort. But what if you want to create a type that only transforms some of the properties, based on their values? That's where things get really interesting.

Say you have a list of properties that you want to transform to string:

const propertiesToTransform = ["foo", "baz"] as const;
Enter fullscreen mode Exit fullscreen mode

You can use a conditional type to create a new type that transforms only the properties in the list to string:

type MyConditionalStringInterface = {
  [K in keyof MyInterface]: K extends typeof propertiesToTransform[number] ? string : MyInterface[K];
}
Enter fullscreen mode Exit fullscreen mode

This creates a new type called MyConditionalStringInterface that has the same properties as MyInterface, but with only the properties in propertiesToTransform set to string.

const myConditionalStringInterface: MyConditionalStringInterface = {
  foo: "hello",
  bar: 42,
  baz: true
};
Enter fullscreen mode Exit fullscreen mode

This is just scratching the surface of what you can do with mapped types. You can use them to create types that depend on the values of your variables, types that filter out certain properties, and much more. With a little creativity, you can unleash the full power of Typescript's type system and write even more robust and flexible code.

So the next time you're working with Typescript, keep mapped types in mind. They might just be the key to unlocking the next level of your code.

Top comments (0)