Skip to main content

Lesson 2 of 8

`keyof` and `typeof` - Type-Level Reflection

`keyof T` produces the union of all keys of type T. `typeof x` extracts the TypeScript type of any value x. Together they unlock type-level reflection - building types dynamically from existing values and types without duplication.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

keyof & typeof - Reflection Patterns

keyof & typeof - Reflection Patterns
// ── keyof - all keys of a type as a union ───────────────────
interface Task { id: number; title: string; status: TaskStatus; priority: Priority; }
type TaskKey = keyof Task;   // "id" | "title" | "status" | "priority"

// keyof with generics - the most common use:
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];   // Type-safe: returns T[K], not any
}

const title    = getProperty(task, "title");    // string
const priority = getProperty(task, "priority"); // Priority
// getProperty(task, "invalid");               // ❌ compile error

// ── Pluck - pick values for a list of keys ────────────────────
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
  return items.map((item) => item[key]);
}
const titles = pluck(tasks, "title");   // string[]
const ids    = pluck(tasks, "id");      // number[]

// ── keyof for sorting ─────────────────────────────────────────
function sortBy<T>(items: T[], key: keyof T): T[] {
  return [...items].sort((a, b) => {
    if (a[key] < b[key]) return -1;
    if (a[key] > b[key]) return 1;
    return 0;
  });
}

// ── typeof - extract type from a VALUE ────────────────────────
const defaultTask = {
  status: "todo" as const,
  priority: "medium" as const,
  tags: [] as string[],
};
type TaskDefaults = typeof defaultTask;
// { status: "todo"; priority: "medium"; tags: string[] }

// ── typeof from function - reuse without importing types ───────
function createApiError(code: string, message: string) {
  return { ok: false as const, code, message, timestamp: new Date() };
}
type ApiError = ReturnType<typeof createApiError>;
// { ok: false; code: string; message: string; timestamp: Date }

// ── Deriving unions from object values ───────────────────────
const ROUTES = {
  home:    "/",
  tasks:   "/tasks",
  profile: "/profile",
  admin:   "/admin",
} as const;

type RouteKey  = keyof   typeof ROUTES;   // "home" | "tasks" | "profile" | "admin"
type RoutePath = (typeof ROUTES)[RouteKey]; // "/" | "/tasks" | "/profile" | "/admin"

function navigate(route: RouteKey): void {
  window.location.href = ROUTES[route];
}
navigate("tasks");    // ✅
// navigate("login"); // ❌ Error

Common Mistakes

  • Using string instead of `keyof T` - `function get(obj: object, key: string)` returns `any`. Using `<T, K extends keyof T>` gives you precise return type `T[K]`.
  • Forgetting `as const` when deriving types from values - `typeof obj` on a mutable object gives widened types (`string` not literals). Add `as const` to preserve literals.
  • `typeof` in type position vs value position - `typeof x` in a type context extracts the type; in a value context it's the JS runtime `typeof` operator. They look identical but mean different things.

Tip

Tip

Practice keyof typeof Reflection Patterns in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for `keyof` and `typeof` - Type-Level Reflection

Practice Task

Note

Practice Task - (1) Write a working example of keyof typeof Reflection Patterns from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with keyof typeof Reflection Patterns is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.

Key Takeaways

  • `keyof T` produces the union of all keys of type T.
  • Using string instead of `keyof T` - `function get(obj: object, key: string)` returns `any`. Using `<T, K extends keyof T>` gives you precise return type `T[K]`.
  • Forgetting `as const` when deriving types from values - `typeof obj` on a mutable object gives widened types (`string` not literals). Add `as const` to preserve literals.
  • `typeof` in type position vs value position - `typeof x` in a type context extracts the type; in a value context it's the JS runtime `typeof` operator. They look identical but mean different things.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done