Mapped Types With Conditionals

What

You can combine mapped types and conditional types to perform complex filtering and transformations on an object’s properties.

How

By using a conditional within the value definition of a mapped type, you can effectively “hide” or transform specific fields:

type FilterStrings<T> = {
  [K in keyof T]: T[K] extends string ? T[K] : never;
};

// Resulting object only has properties that were originally strings

Why

This pattern is useful for creating “safe” versions of complex objects. For example, you might want to create a version of a class that only exposes its primitive data fields for display while stripping away internal methods or complex nested objects.

Summary

Conditional mapped types provide the ultimate control over how one object type is transformed into another.