JavaScript and TypeScript course ยท Module 7: Advanced TypeScript

Mapped Types

18 min read ยท
In this lesson12

"Our park is an incredibly complex organism that constantly evolves. Today we need a registry of all threats, tomorrow we'll need a list of essential supplies, and the day after - a full inventory of dinosaurs along with their statistics," explains John Hammond, founder and director of Jurassic Park. "Every time we must process the same basic data, but in different configurations and formats."

In the world of programming, we often face a similar challenge - transforming existing data types into new forms that better fit specific requirements. TypeScript offers an elegant solution to this problem in the form of mapped types, which allow transforming existing types in a systematic and type-safe manner.

What are mapped types?

Mapped types in TypeScript allow creating new types based on existing ones by transforming the properties of the original type according to a specified pattern. This works similarly to the map() method for arrays in JavaScript, but at the type level - instead of transforming values in an array, we transform properties in a type.

The basic syntax of a mapped type looks as follows:

type MappedType<T> = {
  [K in keyof T]: TransformedType
}

In this schema:

  • T is the source type
  • K in keyof T iterates through all keys of type T
  • TransformedType is the new type that will be assigned to each property

Simple example: Readonly

One of the simplest examples of a mapped type is Readonly<T>, which creates a new type where all properties of the source type T are read-only:

type Readonly<T> = {
  readonly [K in keyof T]: T[K];
};

Let's apply this to our Jurassic Park example:

// Dinosaur type definition
interface Dinosaur {
  id: string;
  name: string;
  species: string;
  age: number;
  weight: number;
  diet: "carnivore" | "herbivore" | "omnivore";
  enclosure: string;
}

// Creating an immutable dinosaur type
type ReadonlyDinosaur = Readonly<Dinosaur>;

// Usage
const trex: ReadonlyDinosaur = {
  id: "TREX-01",
  name: "Rexy",
  species: "Tyrannosaurus Rex",
  age: 7,
  weight: 7500,
  diet: "carnivore",
  enclosure: "Paddock 9"
};

// This won't compile - properties are read-only
// trex.name = "Rex"; // Error: Cannot assign to 'name' because it is a read-only property

Changing property modifiers

Mapped types allow not only transforming property types, but also adding, removing, or modifying modifiers such as readonly or ? (optionality).

Adding modifiers

// Creates a type where all properties are optional
type Partial<T> = {
  [K in keyof T]?: T[K];
};

// Usage
type PartialDinosaur = Partial<Dinosaur>;

// Object can contain only some properties
const newDino: PartialDinosaur = {
  species: "Velociraptor",
  diet: "carnivore"
};

Removing modifiers

We can also remove modifiers using the - sign:

// Creates a type where all properties are required
type Required<T> = {
  [K in keyof T]-?: T[K];
};

// Suppose we have a type with optional properties
interface OptionalDinosaur {
  id: string;
  name: string;
  species: string;
  age?: number;
  weight?: number;
  diet?: "carnivore" | "herbivore" | "omnivore";
  enclosure?: string;
}

// We create a type where all properties are required
type RequiredDinosaur = Required<OptionalDinosaur>;

// This won't compile - missing required properties
// const incompleteDino: RequiredDinosaur = {
//   id: "VEL-02",
//   name: "Blue",
//   species: "Velociraptor"
// };

Transforming property types

Besides modifying property modifiers, we can also transform the types of the properties themselves:

// Transforms all properties to strings
type StringifiedDinosaur = {
  [K in keyof Dinosaur]: string;
};

const strDino: StringifiedDinosaur = {
  id: "TREX-01",
  name: "Rexy",
  species: "Tyrannosaurus Rex",
  age: "7",           // Must be string, not number
  weight: "7500",     // Must be string, not number
  diet: "carnivore",
  enclosure: "Paddock 9"
};

Conditional mapped types

We can combine mapped types with conditional types to selectively transform properties depending on their type:

// Transforms only numeric properties to strings
type StringifyNumericProps<T> = {
  [K in keyof T]: T[K] extends number ? string : T[K];
};

// Usage
type DinosaurWithStringifiedNumbers = StringifyNumericProps<Dinosaur>;

const mixedDino: DinosaurWithStringifiedNumbers = {
  id: "TREX-01",
  name: "Rexy",
  species: "Tyrannosaurus Rex",
  age: "7",           // Must be string (originally number)
  weight: "7500",     // Must be string (originally number)
  diet: "carnivore",  // Still a literal union
  enclosure: "Paddock 9"
};

Practical applications of mapped types

Creating a configuration type based on an existing type

// Dinosaur parameter type definitions
interface DinosaurParameters {
  maxSpeed: number;        // km/h
  length: number;          // meters
  height: number;          // meters
  intelligence: number;    // scale 1-10
  aggressionLevel: number; // scale 1-10
  socialBehavior: "solitary" | "pair" | "pack";
}

// We create a configuration type where all parameters are modifiable
type DinosaurParametersConfig = {
  [K in keyof DinosaurParameters]: {
    min: number;
    max: number;
    default: DinosaurParameters[K];
    description: string;
  };
};

// Usage
const velociraptorConfig: DinosaurParametersConfig = {
  maxSpeed: {
    min: 30,
    max: 70,
    default: 50,
    description: "Maximum running speed in km/h"
  },
  length: {
    min: 1.5,
    max: 2.5,
    default: 2.0,
    description: "Body length in meters"
  },
  height: {
    min: 0.5,
    max: 1.0,
    default: 0.8,
    description: "Height in meters"
  },
  intelligence: {
    min: 1,
    max: 10,
    default: 9,
    description: "Intelligence level on a scale of 1-10"
  },
  aggressionLevel: {
    min: 1,
    max: 10,
    default: 8,
    description: "Aggression level on a scale of 1-10"
  },
  socialBehavior: {
    min: 0,
    max: 2,
    default: "pack",
    description: "Social behavior: solitary, pair, or pack"
  }
};

Creating forms based on a data model

// Data model definition
interface DinosaurRecord {
  id: string;
  name: string;
  species: string;
  age: number;
  diet: "carnivore" | "herbivore" | "omnivore";
  healthStatus: "healthy" | "sick" | "critical";
  lastCheckup: Date;
}

// Form type with validation
type DinosaurFormValidation = {
  [K in keyof DinosaurRecord]: {
    required: boolean;
    validator?: (value: DinosaurRecord[K]) => boolean;
    errorMessage?: string;
  };
};

// Implementation
const dinoFormValidation: DinosaurFormValidation = {
  id: {
    required: true,
    validator: (id) => /^DINO-\d{3}$/.test(id),
    errorMessage: "ID must be in DINO-XXX format, where X is a digit"
  },
  name: {
    required: true,
    validator: (name) => name.length >= 2 && name.length <= 50,
    errorMessage: "Name must be between 2 and 50 characters"
  },
  species: {
    required: true
  },
  age: {
    required: true,
    validator: (age) => age > 0 && age < 30,
    errorMessage: "Age must be between 0 and 30 years"
  },
  diet: {
    required: true
  },
  healthStatus: {
    required: true
  },
  lastCheckup: {
    required: true,
    validator: (date) => date <= new Date(),
    errorMessage: "Last checkup date cannot be in the future"
  }
};

Tracking changes in objects

// Type identifying which fields have changed
type Changed<T> = {
  [K in keyof T]: boolean;
};

// Function tracking changes in an object
function trackChanges<T>(original: T, updated: T): Changed<T> {
  const result = {} as Changed<T>;

  for (const key in original) {
    result[key] = original[key] !== updated[key];
  }

  return result;
}

// Usage example
const originalDino: Dinosaur = {
  id: "TREX-01",
  name: "Rexy",
  species: "Tyrannosaurus Rex",
  age: 7,
  weight: 7500,
  diet: "carnivore",
  enclosure: "Paddock 9"
};

const updatedDino: Dinosaur = {
  id: "TREX-01",
  name: "Rexy",
  species: "Tyrannosaurus Rex",
  age: 8,          // Changed
  weight: 8000,    // Changed
  diet: "carnivore",
  enclosure: "Paddock 10" // Changed
};

const changes = trackChanges(originalDino, updatedDino);
console.log(changes);
// Result: { id: false, name: false, species: false, age: true, weight: true, diet: false, enclosure: true }

Advanced mapped type techniques

Filtering keys based on value types

We can use mapped types together with conditional types to filter object keys based on their value types:

// Selects keys whose values are of a specific type
type FilterKeys<T, U> = {
  [K in keyof T]: T[K] extends U ? K : never;
}[keyof T];

// Selects a subset of an object based on value type
type SubType<T, U> = {
  [K in FilterKeys<T, U>]: T[K];
};

// Example usage: selecting only numeric properties
type NumericDinosaurProps = SubType<Dinosaur, number>;
// Result: { age: number; weight: number; }

// Usage
const dinoStats: NumericDinosaurProps = {
  age: 7,
  weight: 7500
};

Recursive mapped types

We can also create recursive mapped types that transform nested structures:

// Recursively makes everything read-only
type DeepReadonly<T> = {
  readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K];
};

// Nested data structure
interface ParkSystem {
  name: string;
  status: "online" | "offline" | "maintenance";
  subsystems: {
    security: {
      cameras: number;
      fences: {
        powered: boolean;
        voltage: number;
      }[];
    };
    power: {
      mainGenerator: {
        output: number;
        fuel: number;
      };
      backupGenerator: {
        output: number;
        fuel: number;
      };
    };
  };
}

// Creating a deeply immutable version
type ReadonlyParkSystem = DeepReadonly<ParkSystem>;

const parkSystem: ReadonlyParkSystem = {
  name: "Jurassic Park Control System",
  status: "online",
  subsystems: {
    security: {
      cameras: 48,
      fences: [
        { powered: true, voltage: 10000 },
        { powered: true, voltage: 10000 }
      ]
    },
    power: {
      mainGenerator: {
        output: 8000,
        fuel: 75
      },
      backupGenerator: {
        output: 3000,
        fuel: 100
      }
    }
  }
};

// Cannot modify any property, even nested ones
// parkSystem.status = "offline"; // Error
// parkSystem.subsystems.security.cameras = 50; // Error
// parkSystem.subsystems.security.fences[0].powered = false; // Error

Advanced example: Park resource management system

Below is an advanced example using mapped types to create a flexible resource management system for Jurassic Park:

// --- Base type definitions ---

// Base interface for all park resources
interface ParkResource {
  id: string;
  name: string;
  location: string;
  status: "operational" | "maintenance" | "offline";
  lastUpdated: Date;
}

// Different resource types
interface Dinosaur extends ParkResource {
  type: "dinosaur";
  species: string;
  diet: "carnivore" | "herbivore" | "omnivore";
  dangerLevel: 1 | 2 | 3 | 4 | 5;
}

interface Vehicle extends ParkResource {
  type: "vehicle";
  model: string;
  capacity: number;
  fuelLevel: number;
}

interface Facility extends ParkResource {
  type: "facility";
  purpose: "visitor" | "research" | "maintenance" | "security";
  size: number; // in mยฒ
  capacity: number;
}

interface Employee extends ParkResource {
  type: "employee";
  role: string;
  department: "management" | "scientific" | "technical" | "security" | "visitor";
  clearanceLevel: 1 | 2 | 3 | 4 | 5;
}

// Union of all resource types
type Resource = Dinosaur | Vehicle | Facility | Employee;

// --- Mapped types for resource management ---

// Type for storing resource references
type ResourceReferences = {
  [K in Resource["type"]]: string[]; // Array of IDs for each type
};

// Type for registering management processes for each resource type
type ResourceManagementProcesses = {
  [K in Resource["type"]]: {
    create: (data: Omit<Extract<Resource, { type: K }>, "id" | "lastUpdated">) => string;
    update: (id: string, data: Partial<Extract<Resource, { type: K }>>) => boolean;
    delete: (id: string) => boolean;
    audit: (id: string) => AuditReport<Extract<Resource, { type: K }>>;
  };
};

// Type for audit reports
type AuditReport<T extends ParkResource> = {
  resource: T;
  issues: string[];
  recommendations: string[];
  complianceScore: number;
  auditDate: Date;
};

// Type for resource access permissions
type ResourceAccessPermissions = {
  [K in Resource["type"]]: {
    read: string[];   // Roles that can read
    write: string[];  // Roles that can modify
    delete: string[]; // Roles that can delete
  };
};

// Type for resource alert statuses
type ResourceAlertStatuses = {
  [K in Resource["type"]]?: {
    [ID: string]: {
      level: "info" | "warning" | "critical";
      message: string;
      timestamp: Date;
      acknowledged: boolean;
    }[];
  };
};

// Type for resource statistics
type ResourceStatistics = {
  [K in Resource["type"]]: {
    total: number;
    operational: number;
    maintenance: number;
    offline: number;
    utilizationRate: number; // %
  };
};

// Type for form metadata
type ResourceFormMetadata = {
  [K in Resource["type"]]: {
    [Field in keyof Extract<Resource, { type: K }>]: {
      label: string;
      required: boolean;
      type: "text" | "number" | "select" | "date" | "checkbox";
      options?: string[]; // For select fields
      validation?: RegExp; // For text validation
      min?: number;       // For number fields
      max?: number;       // For number fields
      helpText?: string;  // Help text
    };
  };
};

// --- Example implementation ---

// Example form metadata implementation
const formMetadata: ResourceFormMetadata = {
  dinosaur: {
    id: { label: "ID", required: true, type: "text", validation: /^DINO-\d{3}$/, helpText: "Format: DINO-XXX" },
    name: { label: "Name", required: true, type: "text" },
    type: { label: "Type", required: true, type: "text" },
    location: { label: "Location", required: true, type: "text" },
    status: {
      label: "Status",
      required: true,
      type: "select",
      options: ["operational", "maintenance", "offline"]
    },
    lastUpdated: { label: "Last updated", required: true, type: "date" },
    species: { label: "Species", required: true, type: "text" },
    diet: {
      label: "Diet",
      required: true,
      type: "select",
      options: ["carnivore", "herbivore", "omnivore"]
    },
    dangerLevel: {
      label: "Danger level",
      required: true,
      type: "select",
      options: ["1", "2", "3", "4", "5"],
      helpText: "1 - Gentle, 5 - Extremely dangerous"
    }
  },
  vehicle: {
    id: { label: "ID", required: true, type: "text", validation: /^VEH-\d{3}$/, helpText: "Format: VEH-XXX" },
    name: { label: "Name", required: true, type: "text" },
    type: { label: "Type", required: true, type: "text" },
    location: { label: "Location", required: true, type: "text" },
    status: {
      label: "Status",
      required: true,
      type: "select",
      options: ["operational", "maintenance", "offline"]
    },
    lastUpdated: { label: "Last updated", required: true, type: "date" },
    model: { label: "Model", required: true, type: "text" },
    capacity: { label: "Capacity", required: true, type: "number", min: 1, max: 20 },
    fuelLevel: { label: "Fuel level", required: true, type: "number", min: 0, max: 100, helpText: "In percent" }
  },
  facility: {
    id: { label: "ID", required: true, type: "text", validation: /^FAC-\d{3}$/, helpText: "Format: FAC-XXX" },
    name: { label: "Name", required: true, type: "text" },
    type: { label: "Type", required: true, type: "text" },
    location: { label: "Location", required: true, type: "text" },
    status: {
      label: "Status",
      required: true,
      type: "select",
      options: ["operational", "maintenance", "offline"]
    },
    lastUpdated: { label: "Last updated", required: true, type: "date" },
    purpose: {
      label: "Purpose",
      required: true,
      type: "select",
      options: ["visitor", "research", "maintenance", "security"]
    },
    size: { label: "Size", required: true, type: "number", min: 10, helpText: "In square meters" },
    capacity: { label: "Capacity", required: true, type: "number", min: 1 }
  },
  employee: {
    id: { label: "ID", required: true, type: "text", validation: /^EMP-\d{3}$/, helpText: "Format: EMP-XXX" },
    name: { label: "Full name", required: true, type: "text" },
    type: { label: "Type", required: true, type: "text" },
    location: { label: "Work station", required: true, type: "text" },
    status: {
      label: "Status",
      required: true,
      type: "select",
      options: ["operational", "maintenance", "offline"]
    },
    lastUpdated: { label: "Last data update", required: true, type: "date" },
    role: { label: "Position", required: true, type: "text" },
    department: {
      label: "Department",
      required: true,
      type: "select",
      options: ["management", "scientific", "technical", "security", "visitor"]
    },
    clearanceLevel: {
      label: "Clearance level",
      required: true,
      type: "select",
      options: ["1", "2", "3", "4", "5"],
      helpText: "1 - Basic, 5 - Full access"
    }
  }
};

// Example access permissions
const accessPermissions: ResourceAccessPermissions = {
  dinosaur: {
    read: ["management", "scientific", "technical", "security", "visitor"],
    write: ["management", "scientific"],
    delete: ["management"]
  },
  vehicle: {
    read: ["management", "technical", "security"],
    write: ["management", "technical"],
    delete: ["management"]
  },
  facility: {
    read: ["management", "technical", "security"],
    write: ["management", "technical"],
    delete: ["management"]
  },
  employee: {
    read: ["management"],
    write: ["management"],
    delete: ["management"]
  }
};

// Example statistics
const resourceStats: ResourceStatistics = {
  dinosaur: {
    total: 15,
    operational: 12,
    maintenance: 2,
    offline: 1,
    utilizationRate: 80
  },
  vehicle: {
    total: 25,
    operational: 20,
    maintenance: 3,
    offline: 2,
    utilizationRate: 75
  },
  facility: {
    total: 12,
    operational: 10,
    maintenance: 1,
    offline: 1,
    utilizationRate: 85
  },
  employee: {
    total: 120,
    operational: 115,
    maintenance: 0,
    offline: 5,
    utilizationRate: 90
  }
};

// Example alerts
const alertStatuses: ResourceAlertStatuses = {
  dinosaur: {
    "DINO-001": [
      {
        level: "warning",
        message: "Elevated aggression level over the last 24 hours",
        timestamp: new Date(),
        acknowledged: false
      }
    ],
    "DINO-005": [
      {
        level: "critical",
        message: "Dinosaur outside designated enclosure!",
        timestamp: new Date(),
        acknowledged: true
      }
    ]
  },
  facility: {
    "FAC-003": [
      {
        level: "warning",
        message: "Cooling system failure detected",
        timestamp: new Date(),
        acknowledged: false
      }
    ]
  }
};

// Report generator using mapped types
function generateResourceReport<T extends Resource["type"]>(
  resourceType: T,
  detailed: boolean = false
): {
  type: T;
  stats: ResourceStatistics[T];
  alerts: ResourceAlertStatuses[T] | undefined;
  resources?: Extract<Resource, { type: T }>[];
} {
  // In a real implementation, data would be fetched from a database
  return {
    type: resourceType,
    stats: resourceStats[resourceType],
    alerts: alertStatuses[resourceType],
    // Add resource list only if detailed is true
    ...(detailed ? { resources: [] as any } : {})
  };
}

// Usage example
const dinosaurReport = generateResourceReport("dinosaur", true);
console.log(`Dinosaur report:
- Total count: ${dinosaurReport.stats.total}
- Operational: ${dinosaurReport.stats.operational}
- Under maintenance: ${dinosaurReport.stats.maintenance}
- Offline: ${dinosaurReport.stats.offline}
- Utilization rate: ${dinosaurReport.stats.utilizationRate}%
`);

// Display alerts
if (dinosaurReport.alerts) {
  console.log("Active alerts:");
  Object.entries(dinosaurReport.alerts).forEach(([dinoId, alerts]) => {
    alerts.forEach(alert => {
      console.log(`- [${alert.level.toUpperCase()}] ${dinoId}: ${alert.message}`);
    });
  });
}

Built-in mapped types in TypeScript

TypeScript has several built-in mapped types that are very useful in everyday work:

  1. Partial<T> - Creates a type where all properties of T are optional

    type Partial<T> = { [P in keyof T]?: T[P]; };
  2. Required<T> - Creates a type where all properties of T are required

    type Required<T> = { [P in keyof T]-?: T[P]; };
  3. Readonly<T> - Creates a type where all properties of T are read-only

    type Readonly<T> = { readonly [P in keyof T]: T[P]; };
  4. Record<K, T> - Creates a type with keys K and values of type T

    type Record<K extends keyof any, T> = { [P in K]: T; };
  5. Pick<T, K> - Selects a subset of properties K from type T

    type Pick<T, K extends keyof T> = { [P in K]: T[P]; };
  6. Omit<T, K> - Creates a type with all properties of T except those listed in K

    type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
  7. Extract<T, U> - Extracts from T those types that are assignable to U

    type Extract<T, U> = T extends U ? T : never;
  8. Exclude<T, U> - Excludes from T those types that are assignable to U

    type Exclude<T, U> = T extends U ? never : T;
  9. NonNullable<T> - Excludes null and undefined from T

    type NonNullable<T> = T extends null | undefined ? never : T;
  10. Parameters<T> - Extracts parameter types from a function type

    type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;
  11. ReturnType<T> - Extracts the return type from a function type

    type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;

These built-in mapped types are extremely useful and allow for more concise and elegant solutions to many problems.

When to use mapped types?

Mapped types are especially useful in the following scenarios:

  1. Transforming existing types - when you need to create a variant of an existing type (e.g., Readonly<T>, Partial<T>)

  2. Building forms and validations - when creating dynamic forms based on a data model

  3. Configurations and metadata - when you need to create a configuration or metadata structure for each property of a type

  4. API handling - when you need to transform types to a format required by an API

  5. Generating utility types - when creating utility types that operate on other types

Template literal types

TypeScript offers yet another advanced type mechanism - template literal types. They allow creating new string types through interpolation, similar to template literals in JavaScript, but at the type level.

// Basic template literal types
type DinoEvent = `on${string}`;

// Only strings starting with "on" are accepted
const event1: DinoEvent = "onClick";     // OK
const event2: DinoEvent = "onEscape";    // OK
// const event3: DinoEvent = "escape";   // Error!

// Combining with union types
type Species = "TRex" | "Raptor" | "Triceratops";
type DinoAction = "feed" | "track" | "relocate";

// Generates: "feedTRex" | "feedRaptor" | ... (all combinations)
type DinoCommand = `${DinoAction}${Species}`;

Template literal types are especially useful for creating precise types for event names, configuration keys, or API paths. They work on the principle of string interpolation, but at the type system level - the TypeScript compiler generates all possible combinations.

Summary

Mapped types are a powerful TypeScript mechanism that allows systematic type transformation. Just as in Jurassic Park, where the same dinosaur data can be processed in different ways depending on needs, mapped types allow us to create new types based on existing ones, adapting them to specific requirements.

Thanks to mapped types, we can create more flexible, type-safe APIs, forms, validations, and many other data structures. This mechanism is especially powerful when combined with other advanced TypeScript features, such as conditional types or type inference.

As you gain more experience with TypeScript, mapped types will become an indispensable tool in your arsenal, allowing you to create more expressive, safe, and elegant solutions.

Code for this lesson: index.ts
// Mapped types - Jurassic Park
console.log("=== MAPPED TYPES ===\n");

// ===========================================
// 1. Built-in mapped types
// ===========================================

interface DinosaurConfig {
  name: string;
  species: string;
  weight: number;
  height: number;
  dangerLevel: number;
  isContained: boolean;
}

// Readonly<T> - all fields read-only
type FrozenDino = Readonly<DinosaurConfig>;

// Partial<T> - all fields optional
type DinoUpdate = Partial<DinosaurConfig>;

// Pick<T, K> - picking a subset of fields
type DinoSummary = Pick<DinosaurConfig, "name" | "species" | "dangerLevel">;

// Omit<T, K> - leaving fields out
type DinoPublic = Omit<DinosaurConfig, "isContained" | "dangerLevel">;

// Record<K, T> - mapping keys to a type
type DinoRegistry = Record<string, DinosaurConfig>;

// ===========================================
// 2. Custom mapped types
// ===========================================

// All fields as nullable
type Nullable<T> = {
  [K in keyof T]: T[K] | null;
};

// All fields as optional and nullable
type OptionalNullable<T> = {
  [K in keyof T]?: T[K] | null;
};

// Numeric fields turned into strings (formatting)
type Stringify<T> = {
  [K in keyof T]: T[K] extends number ? string : T[K];
};

// Only the fields with a numeric type
type NumericFields<T> = {
  [K in keyof T as T[K] extends number ? K : never]: T[K];
};

// Adding a 'get' prefix to the field names
type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};

// ===========================================
// 3. Practical uses
// ===========================================

// A form with validation - each field has an error
type FormErrors<T> = {
  [K in keyof T]?: string;
};

// A loading state for each field
type LoadingState<T> = {
  [K in keyof T]: {
    value: T[K];
    isLoading: boolean;
    error?: string;
  };
};

// ===========================================
// Test
// ===========================================

// Readonly
console.log("--- Readonly ---");
const frozen: FrozenDino = {
  name: "Rexy",
  species: "T-Rex",
  weight: 8000,
  height: 5.5,
  dangerLevel: 10,
  isContained: true
};
console.log("Frozen:", frozen.name);
// frozen.name = "New"; // Error! - readonly

// Partial - a partial update
console.log("\n--- Partial ---");
function updateDino(current: DinosaurConfig, updates: DinoUpdate): DinosaurConfig {
  return { ...current, ...updates };
}
const updated = updateDino(frozen as DinosaurConfig, { weight: 8200, height: 5.6 });
console.log("After the update:", updated.weight, "kg,", updated.height, "m");

// Pick
console.log("\n--- Pick ---");
const summary: DinoSummary = { name: "Rexy", species: "T-Rex", dangerLevel: 10 };
console.log("Summary:", JSON.stringify(summary));

// Record
console.log("\n--- Record ---");
const registry: DinoRegistry = {
  "DINO-001": { name: "Rexy", species: "T-Rex", weight: 8000, height: 5.5, dangerLevel: 10, isContained: true },
  "DINO-002": { name: "Blue", species: "Velociraptor", weight: 15, height: 1.8, dangerLevel: 8, isContained: true },
};
Object.entries(registry).forEach(([id, dino]) => {
  console.log(`${id}: ${dino.name} (${dino.species})`);
});

// Nullable
console.log("\n--- Nullable (custom) ---");
const maybeDino: Nullable<DinoSummary> = {
  name: "Unknown",
  species: null,
  dangerLevel: null
};
console.log("Partial data:", JSON.stringify(maybeDino));

// Stringify
console.log("\n--- Stringify (custom) ---");
const formatted: Stringify<DinoSummary> = {
  name: "Rexy",
  species: "T-Rex",
  dangerLevel: "10/10" // number -> string
};
console.log("Formatted:", JSON.stringify(formatted));

// FormErrors
console.log("\n--- FormErrors ---");
type DinoForm = Pick<DinosaurConfig, "name" | "weight" | "species">;
const errors: FormErrors<DinoForm> = {
  name: "Name is required",
  weight: "Weight must be positive"
};
Object.entries(errors).forEach(([field, error]) => {
  console.log(`  ${field}: ${error}`);
});

console.log("\nMapped types = transforming types like data!");

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What are template literal types in TypeScript?

Hands-on tasks in the game

  • Code editor

    Create custom mapped types for the park permissions system

  • Click in order

    Arrange the elements of the Readonly mapped type:

  • Click in order

    Arrange the elements of a type based on keyof and typeof:

  • Vertical ordering

    Order the steps for creating a generic utility type:

  1. QuestionTemplate Literal Types
  2. Coding taskMapped Types
  3. Click in orderSorting: Mapped Type
  4. Click in orderSorting: keyof + typeof
  5. Put in orderSteps to Create a Generic Utility Type

Useful articles