Skip to content

Mapped Types, keyof, and Template Literal Types (Interview-Ready)

How keyof + mapped types work, and how template literal types unlock powerful typed APIs.

Rajesh DhimanFebruary 08, 20261 min read
On this page

30‑second interview answer

keyof gives you the union of keys of a type. Mapped types iterate over keys to build new types (like Partial, Pick, Record). Template literal types let you construct string unions (like onClick, getUserId) and are great for typed event names and CSS variables. Together, they power many advanced TS patterns.


keyof

type User = { id: string; name: string; isAdmin: boolean };
 
type UserKey = keyof User; // 'id' | 'name' | 'isAdmin'

Mapped types

Build a Partial (how TS does it conceptually)

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

Pick a subset

type MyPick<T, K extends keyof T> = {
  [P in K]: T[P];
};

Readonly

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

Template literal types

type EventName = 'click' | 'focus';
 
type HandlerName = `on${Capitalize<EventName>}`;
// 'onClick' | 'onFocus'

Practical use: typed event map

type Events = {
  click: { x: number; y: number };
  focus: { elementId: string };
};
 
type EventKey = keyof Events;
 
type ListenerName = `on${Capitalize<string & EventKey>}`;

Common pitfalls

  • keyof includes only keys, not values.
  • Mapped types can accidentally create unions you didn’t expect (test with examples).
  • Template literal types can get complex—keep them small and documented.

Mini Q&A

Q1: What is keyof used for?

  • building safe APIs that depend on object keys.

Q2: What are mapped types?

  • type-level loops over keys.

Q3: Where do template literal types help?

  • typed string-based APIs: routes, event names, CSS variables.

Summary checklist

  • I can explain keyof.
  • I can write a mapped type.
  • I can show a template literal type use case.
Companion Book

Looking for structured, offline interview prep?

Free online lessons • Portable Amazon Kindle / Paperback

Frontend Interview Guide (2025 Edition) cover
Recommended for React & Frontend Rounds

Frontend Interview Guide (2025 Edition)

By Rajesh Dhiman

Comprehensive preparation covering React internals, Web Performance, CSS architecture, and system design questions.

View on Amazon ↗Kindle & Paperback
JavaScript Interview Guide cover
Recommended for Core JS Rounds

JavaScript Interview Guide

By Rajesh Dhiman

Deep dive into the Event Loop, microtask draining, closures, prototypal inheritance, and asynchronous execution patterns.

View on Amazon ↗Kindle & Paperback

Note: All lessons on Frontend Interview remain completely free to read online. As an Amazon Associate, we may earn from qualifying purchases.

RD

Written by Rajesh Dhiman

Authored by Rajesh Dhiman and engineered at Eunix Tech. Focused on deep-dive frontend engineering, JavaScript runtime internals, React architecture, and web performance.