Course contentsShow
← TypeScript
Lesson 757 of 1,79617. Mapped TypesFree lesson

Conditional Key Remapping

Apply conditional types within as clauses to remap keys based on type conditions.

What You'll Learn

You'll learn how to apply conditional types inside as clauses to remap object keys only when specific type conditions are met, giving you fine-grained control over which properties appear in your mapped types.


The Core Idea

You already know how to use the as clause to transform or filter keys in mapped types. Now we're adding conditional logic to that remapping: you can check a property's type and decide whether to rename it, keep it as-is, or exclude it altogether.

The pattern looks like this:

{ [K in keyof T as <condition> ? <newKey> : <alternative>]: <valueType> }

This lets you say things like:

  • "Only include properties that are functions"
  • "Rename properties only if they're optional"
  • "Transform keys only if their value is a string"

Plain-English Analogy

Imagine sorting files into folders, but with rules: "If the file is a PDF, put it in /documents; if it's an image, put it in /photos; otherwise, exclude it entirely." Conditional key remapping applies that same branching logic to TypeScript properties.


How It Works

You use a conditional type inside the as clause. The condition typically checks the property's value type using T[K].

Example: Only include string properties:

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

type User = { name: string; age: number; email: string };
type Strings = StringPropsOnly<User>;
// { name: string; email: string } — age excluded

Example: Prefix only number properties:

type PrefixNumbers<T> = {
  [K in keyof T as T[K] extends number ? `num_${K & string}` : K]: T[K]
};

type Data = { count: number; label: string };
type Prefixed = PrefixNumbers<Data>;
// { num_count: number; label: string }

Common Patterns

Filter and rename in one pass:

type GettersOnly<T> = {
  [K in keyof T as T[K] extends () => any ? `get${Capitalize<K & string>}` : never]: T[K]
};

Keep keys conditionally:

type RequiredKeys<T> = {
  [K in keyof T as undefined extends T[K] ? never : K]: T[K]
};

When to Use This

  • Building type-safe API response mappers that only include certain field types
  • Creating validation schemas that filter out non-primitive properties
  • Generating branded or prefixed types from configuration objects

Key Takeaway: Conditional key remapping combines as with conditional types to create mapped types that selectively transform or exclude properties based on their types, enabling powerful compile-time filtering and transformation logic.