惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
GbyAI
GbyAI
F
Fortinet All Blogs
Y
Y Combinator Blog
I
InfoQ
Microsoft Azure Blog
Microsoft Azure Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
Vercel News
Vercel News
T
The Blog of Author Tim Ferriss
P
Proofpoint News Feed
S
Schneier on Security
NISL@THU
NISL@THU
The Hacker News
The Hacker News
Simon Willison's Weblog
Simon Willison's Weblog
The GitHub Blog
The GitHub Blog
MyScale Blog
MyScale Blog
Cisco Talos Blog
Cisco Talos Blog
F
Full Disclosure
P
Palo Alto Networks Blog
T
The Exploit Database - CXSecurity.com
Know Your Adversary
Know Your Adversary
A
About on SuperTechFans
The Cloudflare Blog
T
Threat Research - Cisco Blogs
M
MIT News - Artificial intelligence
宝玉的分享
宝玉的分享
雷峰网
雷峰网
Hugging Face - Blog
Hugging Face - Blog
博客园 - 三生石上(FineUI控件)
D
DataBreaches.Net
Martin Fowler
Martin Fowler
H
Help Net Security
B
Blog RSS Feed
B
Blog
爱范儿
爱范儿
V
V2EX
I
Intezer
L
LangChain Blog
WordPress大学
WordPress大学
小众软件
小众软件
美团技术团队
Latest news
Latest news
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Tor Project blog
L
Lohrmann on Cybersecurity
Cyberwarzone
Cyberwarzone
Last Week in AI
Last Week in AI
Project Zero
Project Zero
C
Cybersecurity and Infrastructure Security Agency CISA
V
Visual Studio Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
TypeScript Mapped Types: The Feature That Changes How You Design Types
Kai Thorne · 2026-06-13 · via DEV Community

Kai Thorne

You've written this before:

interface User {
  id: number;
  name: string;
  email: string;
  role: 'admin' | 'user';
}

interface UserFormState {
  id: boolean;
  name: boolean;
  email: boolean;
  role: boolean;
}

A UserFormState where every field is a boolean — did it change? Was it touched? You maintain two types that mirror each other. Add a field to User, forget to update UserFormState, and your types lie to you.

Mapped types solve this. They let you derive one type from another automatically. When User changes, UserFormState updates itself.

Let's start with the basics and work up to the patterns that will change how you architect TypeScript code.


The Syntax: What a Mapped Type Actually Is

A mapped type iterates over the keys of another type and transforms each property. Here's the simplest form:

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

This reads: "for each key K in the set of keys of T, create a property with that key, and give it the same type as T[K]." It's a no-op — it produces an identical type. The power comes from what you do inside the braces.

Let's solve the form state problem:

type FormState<T> = {
  [K in keyof T]: boolean;
};

// Derive from User automatically
type UserFormState = FormState<User>;
//   ^? { id: boolean; name: boolean; email: boolean; role: boolean; }

// Add a field to User — UserFormState updates automatically

One type parameter, one mapped type, zero duplication. Add age: number to User, and UserFormState gets age: boolean without touching a single line.


Modifiers: Making Properties Optional, Readonly, or Mutable

Mapped types can add or remove type modifiers. The two modifiers are readonly and ? (optional).

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

// Make everything optional
type Partial<T> = {
  [K in keyof T]?: T[K];
};

// Remove readonly (make everything writable)
type Mutable<T> = {
  -readonly [K in keyof T]: T[K];
};

// Remove optional (make everything required)
type Required<T> = {
  [K in keyof T]-?: T[K];
};

These aren't theoretical. Readonly<T>, Partial<T>, and Required<T> are built into TypeScript's standard library. But understanding the syntax lets you create your own.

A real example: you have a configuration object that should be frozen after creation, but you want to build it with mutations internally.

interface AppConfig {
  readonly databaseUrl: string;
  readonly apiKey: string;
  readonly port: number;
}

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

function createConfig(): AppConfig {
  // Build with mutations, then cast
  const config: Writable<AppConfig> = {
    databaseUrl: '',
    apiKey: '',
    port: 0,
  };

  config.databaseUrl = process.env.DATABASE_URL!;
  config.apiKey = process.env.API_KEY!;
  config.port = parseInt(process.env.PORT ?? '3000', 10);

  return config as AppConfig;
}

The -readonly modifier strips readonly during construction, then the return type AppConfig freezes it for consumers. Clean, type-safe, and minimal code.


Key Remapping with as (TypeScript 4.1+)

Here's where mapped types get genuinely powerful. You can transform the keys themselves using the as clause:

type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};

interface Person {
  name: string;
  age: number;
}

// Result:
type PersonGetters = Getters<Person>;
//   ^? { getName: () => string; getAge: () => number; }

This isn't just clever syntax. It's how you create type-safe wrappers, API clients, and state managers without manually listing every property.

Filtering Keys

You can also exclude keys by resolving them to never in the as clause:

// Exclude methods, keep only data properties
type DataProperties<T> = {
  [K in keyof T as T[K] extends Function ? never : K]: T[K];
};

type StripMethods<T> = {
  [K in keyof T as T[K] extends (...args: any[]) => any ? never : K]: T[K];
};

class UserService {
  name: string = '';
  age: number = 0;
  save(): Promise<void> { return Promise.resolve(); }
  delete(): Promise<void> { return Promise.resolve(); }
}

type UserData = StripMethods<UserService>;
//   ^? { name: string; age: number; }
//   save() and delete() are gone

This pattern is invaluable when you're building serialization layers. Your API response types shouldn't include methods, but you also shouldn't maintain a parallel type by hand.

Real Example: Type-Safe API Client

Let's put key remapping to work. Say you have a set of API endpoints:

interface Endpoints {
  users: { list: { method: 'GET'; path: '/users'; }; create: { method: 'POST'; path: '/users'; }; };
  products: { list: { method: 'GET'; path: '/products'; }; update: { method: 'PUT'; path: '/products/:id'; }; };
}

// Convert endpoints into a flat set of callable methods
type ApiClient<T> = {
  [K1 in keyof T]: {
    [K2 in keyof T[K1] as `${string & K2}${Capitalize<string & K1>}`]: 
      (params?: any) => Promise<any>;
  };
};

// Usage:
type Client = ApiClient<Endpoints>;
// Result:
// {
//   users: { listUsers: (params?: any) => Promise<any>; createUsers: (params?: any) => Promise<any>; };
//   products: { listProducts: (params?: any) => Promise<any>; updateProducts: (params?: any) => Promise<any>; };
// }

The key remapping works like this:

  1. Outer loop (K1): iterates over the top-level keys (users, products)
  2. Inner loop (K2): iterates over the second-level keys (list, create)
  3. as clause transforms the key name: list + userslistUsers, create + userscreateUsers
  4. Each resolved method returns Promise<any>

The result is a nested client where routes are grouped by resource: client.users.listUsers(). The as clause did the heavy lifting of naming each method without you typing out all the combinations.


Combining Mapped Types with Template Literal Types

Template literal types and mapped types work together to solve real problems.

CSS Property Prefixes

type CSSValue = string | number;

type CSSProperties = {
  margin: CSSValue;
  padding: CSSValue;
  border: CSSValue;
};

type Responsive<T> = {
  [K in keyof T as `${string & K}Mobile`]: T[K];
} & {
  [K in keyof T as `${string & K}Desktop`]: T[K];
};

type ResponsiveCSS = Responsive<CSSProperties>;
//   ^? { marginMobile: CSSValue; marginDesktop: CSSValue;
//        paddingMobile: CSSValue; paddingDesktop: CSSValue;
//        borderMobile: CSSValue; borderDesktop: CSSValue; }

State Machine Event Handlers

type States = 'idle' | 'loading' | 'success' | 'error';

type EventHandlers = {
  [K in States as `onEnter${Capitalize<K>}`]: () => void;
} & {
  [K in States as `onLeave${Capitalize<K>}`]: () => void;
};

// Result:
// { onEnterIdle: () => void; onEnterLoading: () => void;
//   onEnterSuccess: () => void; onEnterError: () => void;
//   onLeaveIdle: () => void; ... }

No more manually typing eight handler signatures that mirror your four states. Add a state — get two new handlers automatically. The compiler enforces completeness.


Conditional Types + Mapped Types = Unstoppable

Conditional types (T extends U ? X : Y) let you transform property values based on the type of each key. Combined with mapped types, this is how you build the most expressive type utilities.

// Convert all Date properties to ISO strings
type DatesToStrings<T> = {
  [K in keyof T]: T[K] extends Date ? string : T[K];
};

interface Event {
  id: number;
  name: string;
  createdAt: Date;
  updatedAt: Date;
  scheduledFor: Date;
}

type SerializedEvent = DatesToStrings<Event>;
//   ^? { id: number; name: string;
//        createdAt: string; updatedAt: string; scheduledFor: string; }

This is the core of serialization. When you send an object over the wire, Date objects become strings. This type enforces that transformation at compile time.

Deep Wrapping: API Response Wrapper

You can wrap an entire type hierarchy using conditional types inside mapped types:

// Wrap every property value in a Result-like container
type DeepResult<T> = {
  [K in keyof T]: T[K] extends object
    ? DeepResult<T[K]> & { success: boolean; error: string | null }
    : { value: T[K]; success: boolean; error: string | null };
};

interface Config {
  database: { host: string; port: number };
  features: { darkMode: boolean; beta: boolean };
}

type ConfigResult = DeepResult<Config>;
// database: DeepResult<{ host: string; port: number }> & { success: boolean; error: string | null }
//   → host: { value: string; success: boolean; error: string | null }
//   → port: { value: number; success: boolean; error: string | null }
// features: same, plus { success: boolean; error: string | null } at each level

Real Example: API Response Transformer

type ApiResponse<T> = {
  data: T;
  error: null | { message: string; code: number };
  meta: {
    page: number;
    totalPages: number;
  };
};

// Flatten into a cleaner client-side type — strip null unions, simplify errors
type FlattenedResponse<T> = {
  [K in keyof T as T[K] extends null | undefined ? never : K]: T[K];
} & {
  error: string | null; // Replace full error object with just a message
};

type ClientResponse = FlattenedResponse<ApiResponse<{ id: number }>>;


Pattern: Type-Safe Event Emitter

Let's build something real. A generic event emitter where each event name maps to its payload type, and on/emit are fully typed.

type EventMap = {
  userLoggedIn: { userId: string; timestamp: number };
  userLoggedOut: { userId: string };
  error: { message: string; code: number; fatal: boolean };
  dataLoaded: { resource: string; items: number };
};

class TypedEmitter<T extends Record<string, unknown>> {
  private handlers = new Map<keyof T, Set<Function>>();

  on<K extends keyof T>(event: K, handler: (payload: T[K]) => void): void {
    if (!this.handlers.has(event)) {
      this.handlers.set(event, new Set());
    }
    this.handlers.get(event)!.add(handler);
  }

  emit<K extends keyof T>(event: K, payload: T[K]): void {
    this.handlers.get(event)?.forEach(handler => handler(payload));
  }

  off<K extends keyof T>(event: K, handler: (payload: T[K]) => void): void {
    this.handlers.get(event)?.delete(handler);
  }
}

// Usage — fully type-checked
const bus = new TypedEmitter<EventMap>();

bus.on('userLoggedIn', (payload) => {
  // payload is { userId: string; timestamp: number }
  console.log(payload.userId); // ✅ typed
  console.log(payload.timestamp); // ✅ typed
  console.log(payload.fatal); // ❌ error: Property 'fatal' does not exist
});

bus.emit('error', { message: 'Disk full', code: 500, fatal: true }); // ✅
bus.emit('userLoggedIn', { userId: 'abc' }); // ❌ missing timestamp

This works because of two mapped type behaviors:

  • T extends Record<string, unknown> constrains the map shape
  • K extends keyof T picks a specific event, and T[K] resolves its payload

No any, no type assertions, no runtime overhead beyond a Map.


Pattern: Form State with Dirty Tracking

Earlier we turned every field to boolean. Let's build something more useful — a dirty-tracking form state that knows both the original type and what changed.

type DirtyState<T> = {
  [K in keyof T]: {
    value: T[K];
    dirty: boolean;
    original: T[K];
  };
};

interface Profile {
  displayName: string;
  bio: string;
  age: number;
  email: string;
}

type ProfileForm = DirtyState<Profile>;
// Each field becomes: { value: string; dirty: boolean; original: string; }

The mapped type eliminates an entire category of bugs. Add a new field to Profile and every form component that uses ProfileForm gets the new field automatically.


When NOT to Use Mapped Types

Mapped types add complexity. They're not always the right tool.

Skip mapped types when:

  1. You have two or three fields. Just write the type. type Status = 'idle' | 'loading' | 'done' is clearer than any derived type.

  2. The mapping is one-to-one with no transformation. type Copy<T> = { [K in keyof T]: T[K] } is useless — just use the original type.

  3. You need runtime behavior. Mapped types only operate at the type level. If you need to actually iterate keys at runtime, you still need Object.keys() or a for...in loop.

  4. Readability suffers. If a mapped type takes more than 30 seconds to understand, extract it behind a well-named utility or add a comment.

Use mapped types when:

  • You're deriving one type from another (form state, serialized version, API client)
  • You're transforming keys systematically (prefix, suffix, filter)
  • You're adding/removing modifiers across the board (readonly, optional)
  • You have a union of string literals and need an object type keyed by them

Where to Go Next

Mapped types are one layer in TypeScript's type system. If this clicked, dive into:

  • Conditional types with infer — extracting types from inside other types
  • Template literal types for string manipulation at the type level
  • Variadic tuple types for type-safe function arguments

The TypeScript handbook is excellent, but the best way to learn is to open your editor and try mapping over your own interfaces. Change a key, add a modifier, see what breaks. That's how the type system stops being a compiler and starts being a tool you design with.


Kai Thorne writes about TypeScript, Python, and building better software. Follow for practical, no-fluff technical content.