Learn TypeScript · 11/14

Advanced Type Manipulation

7 min read

Welcome back, Code Traveler! 🎒

If you’ve made it this far, you are no longer a TypeScript tourist. You are becoming a resident. You know your primitives, your interfaces, and your basic generics. But now, we are going to stop writing types manually and start making TypeScript calculate them for us.

Think of this section as moving from doing math on a napkin to using Excel formulas. It’s about being lazy in the smartest way possible. We are going to look at how to manipulate types dynamically so your code creates a "safety net" that grows and shrinks automatically as your data changes.

Let's dive into the wizardry. ✨


1. The keyof Operator: Extracting Object Keys 🗝️

The Problem: The "Fat Finger" Syndrome

Imagine you are building a function to get a property from an object. In standard JavaScript, you pass the object and a string for the key name. If you make a typo, you get undefined. In a large codebase, this causes silent failures that are annoying to debug.

The Definition

The keyof operator takes an object type and produces a string or numeric literal union of its keys.

The Solution

We use keyof to tell TypeScript: "The second argument of this function MUST be one of the keys existing in the first argument."

typescript
// 1. Let's define a standard User type
interface User {
  id: number;
  name: string;
  email: string;
}

// 2. Using keyof to create a new type
type UserKeys = keyof User; 
// The above is equivalent to: type UserKeys = "id" | "name" | "email";

// 3. Real-world application: A generic "getProperty" function
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const dev = {
  id: 1,
  name: "Quincy",
  email: "[email protected]"
};

// ✅ Valid
const userName = getProperty(dev, "name"); 

// 🛑 Error: Argument of type '"age"' is not assignable to parameter of type '"id" | "name" | "email"'.
// const userAge = getProperty(dev, "age"); 

Industry Insight 🧠

In industry, keyof is the backbone of building typesafe database queries (like ORMs) or form handling libraries. If you rename a database column in your Type definition, keyof ensures every single query in your app attempting to use the old name turns red immediately.


2. The typeof Operator in Type Contexts 📸

The Problem: Double Maintenance

You often write a complex configuration object (a value) for your app. Then, you realize you need a Type for that object to pass it around. Beginners often manually write an interface that matches the object. Now you have two sources of truth. If you update the object, you must remember to update the interface.

The Definition

In TypeScript, typeof refers to the type of a variable or property. Note: This uses the same keyword as JavaScript's runtime typeof, but when used in a type position (after a colon or in a type alias), it is a compile-time operator.

The Solution

Use typeof to snap a "photograph" of your value and turn it into a type.

typescript
// 1. The Source of Truth (Value)
const themeConfig = {
  darkMode: true,
  palette: {
    primary: "#007bff",
    secondary: "#6c757d"
  },
  version: "1.0.0"
};

// 2. Generating the Type automatically
type Theme = typeof themeConfig;

/* 
  TypeScript infers 'Theme' as:
  {
    darkMode: boolean;
    palette: {
      primary: string;
      secondary: string;
    };
    version: string;
  }
*/

// 3. Usage
function loadTheme(t: Theme) {
  // ...
}

⚠️ Important Nuance

TypeScript is smart, but it's literal. If you use const (as above), it infers primitives (boolean, string). If you want the exact values (literals), you combine it with as const:

typescript
const routes = {
  home: "/",
  admin: "/admin"
} as const; // <--- The magic 'as const'

type Routes = typeof routes;
// Result: { readonly home: "/"; readonly admin: "/admin"; }
// Not just strings, but the SPECIFIC strings.

3. Mapped Types: Transforming Existing Types 🗺️

The Problem: The Copy-Paste Nightmare

You have a Product interface. Now you need a ProductUpdateDTO (Data Transfer Object) where all fields are optional (because you might only update the price). Then you need a ReadOnlyProduct so no one changes ID. Creating three separate interfaces creates tech debt.

The Definition

Mapped types build on the syntax of index signatures to declare property types. They act like a loop (think .map() in arrays) that iterates through keys of an existing type to create a new one.

The Solution

We use the syntax [Key in keyof Type] to iterate.

typescript
interface Course {
  id: number;
  title: string;
  difficulty: string;
}

// 1. Creating a type where everything is boolean (e.g., for permissions)
type CoursePermissions = {
  [K in keyof Course]: boolean;
};
// Result: { id: boolean; title: boolean; difficulty: boolean; }

// 2. Creating a Partial type (Make everything optional)
// (This is actually how the built-in Partial<T> utility works!)
type Optional<T> = {
  [K in keyof T]?: T[K]; // <--- The '?' makes it optional
};

type UpdateCourse = Optional<Course>;
// Result: { id?: number; title?: string; difficulty?: string; }

Modifiers (+ and -)

You can add or remove modifiers like readonly or ?.

typescript
// Remove 'readonly' attributes from a type
type Mutable<T> = {
  -readonly [K in keyof T]: T[K]; 
};

// Remove 'optional' attributes (Make everything required)
type Concrete<T> = {
  [K in keyof T]-?: T[K];
};

4. Conditional Types: If/Else Logic for Types 🚦

The Problem: Dynamic Function Returns

Sometimes a function returns a different type based on the input type.

  • Input string -> Return string[]
  • Input number -> Return number[]
  • Input null -> Return never

Overloading functions works, but Conditional Types are cleaner for generic constraints.

The Definition

Conditional types take the form of a ternary operator:
SomeType extends OtherType ? TrueType : FalseType;

The Solution

It asks: "Does the type on the left fit into the type on the right?"

typescript
interface Animal {
  live(): void;
}
interface Dog extends Animal {
  woof(): void;
}

// 1. Basic Condition
type Example1 = Dog extends Animal ? number : string;
// Result: number (Because Dog extends Animal)

type Example2 = RegExp extends Animal ? number : string;
// Result: string (RegExp does not extend Animal)

Practical Industry Use: Extract and Exclude

This is rarely used manually for simple logic, but it is everywhere in utility types.

Let's look at Exclude. Imagine you have a union of types, and you want to remove one.

typescript
type Status = "success" | "warning" | "error" | "loading";

// We want a type that is everything EXCEPT "loading"
// Syntax: T extends U ? never : T
// logic: If the type is 'loading', return 'never' (removes it), else keep it.

type FinishedStatus = Exclude<Status, "loading">;
// Result: "success" | "warning" | "error"

Simulation: The API Response Handler

Imagine a system where an API ID can be a string or number.

typescript
type IdLabel<T> = T extends string ? "ID is a String" : "ID is a Number";

function getIdLabel<T extends string | number>(id: T): IdLabel<T> {
  // Type assertions are often needed inside implementation of conditional types
  // because TS is cautious about the unresolved generic 'T'
  throw "Not implemented"; 
}

const a = getIdLabel("101"); // Type: "ID is a String"
const b = getIdLabel(500);   // Type: "ID is a Number"

Funny Fact 👽

In the early days of TypeScript, before Mapped and Conditional types, libraries like Redux had type definitions that were thousands of lines long, manually listing every possible combination of state changes. Today, those same definitions are just a few lines of "Type Gymnastics." You are literally saving your wrists from Carpal Tunnel by learning this.

Summary Checklist ✅

  1. keyof: Extract keys from an object type (type K = keyof Obj).
  2. typeof: Extract a type from a value (type T = typeof value).
  3. Mapped Types: Loop over keys to change properties ([K in keyof T]).
  4. Conditional Types: Ternary operators for types (T extends U ? X : Y).

📚 References & Further Reading

Challenge

You've been tasked with creating a type-safe data sanitization utility for API responses. Your goal is to implement a generic mapped type called Sanitize<T> that cleans up an object type T according to a set of specific rules.

Your Task

Create the generic utility type Sanitize<T>.

Requirements

The Sanitize<T> type must perform the following transformations:

  1. Make all properties mutable: Remove the readonly modifier from all properties in T.
  2. Exclude all methods: Remove any properties from T whose value is a function type.
  3. Handle nested objects: If a property with the key metadata exists on T, transform its type so that all of its own properties become optional. All other properties should retain their original value types.

You will need to apply this utility to the type of the provided userProfile constant.

Expected result

Your code should correctly define the Sanitize<T> generic utility type. When this utility is applied to typeof userProfile, the resulting SanitizedProfile type should be equivalent to the following structure:

typescript
type SanitizedProfile = {
    // Note: 'id' is now mutable, not readonly
    id: 101;
    username: "ts_wizard";
    email: "[email protected]";
    isActive: true;
    metadata: {
        // Note: 'lastLogin' and 'theme' are now optional
        lastLogin?: Date;
        theme?: "dark";
    };
    // Note: The 'logActivity' property has been completely removed.
};

A correct implementation of Sanitize<T> would combine mapped types with key remapping and conditional types to achieve the desired transformations.

typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.