BeCuriouzBeCuriouz

Learn something new every day

🔷 TypeScript
🔑

keyof & typeof: Deriving Types From Your Values

💡 typeof turns a value into its type and keyof turns a type into a union of its keys — together they let you derive types instead of duplicating them.

Two TypeScript operators let you pull types out of things you already have, so you never repeat yourself. typeof takes a runtime value and gives you its type; keyof takes a type and gives you a union of its property-key names. Note this is the type-level typeof — different from JavaScript's runtime typeof x === 'string' check, even though they share a keyword.

Start with a plain object. Instead of hand-writing a matching interface, ask the compiler to read it for you:

ts
const config = { host: "localhost", port: 8080, ssl: false };

type Config = typeof config;
// { host: string; port: number; ssl: boolean }

type ConfigKey = keyof Config;
// "host" | "port" | "ssl"

The real power comes from combining them, usually with a generic. A type-safe getter can only accept keys that actually exist, and it returns exactly the right value type per key:

ts
function get<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

get(config, "port"); // inferred as number
get(config, "nope"); // ❌ compile error: not a key of config

Here K extends keyof T constrains the key, and T[K] is an indexed access type that looks up the value type. Because everything is derived, editing config automatically updates Config, ConfigKey, and every call site — one source of truth, zero drift.

🔑 keyof & typeof: Deriving Types From Your Values — BeCuriouz