CPCODELAB
TypeScript

keyof, typeof & Indexed Access Types

10 min read

keyof, typeof & Indexed Access Types

keyof

keyof T produces a union of all the known public property names of type T as string (or number or symbol) literal types. It is the foundation of many generic constraints.

ts
interface Config {
  host: string;
  port: number;
  debug: boolean;
}

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

function getConfig<K extends keyof Config>(cfg: Config, key: K): Config[K] {
  return cfg[key];
}

const cfg: Config = { host: "localhost", port: 3000, debug: false };
const host = getConfig(cfg, "host");  // string
const port = getConfig(cfg, "port");  // number

typeof

In type position, typeof extracts the TypeScript type of a JavaScript value. This lets you derive a type from a runtime constant rather than duplicating it.

ts
const defaultSettings = {
  theme: "dark",
  fontSize: 14,
  language: "en"
} as const;

type Settings = typeof defaultSettings;
// { readonly theme: "dark"; readonly fontSize: 14; readonly language: "en" }

type SettingKey = keyof typeof defaultSettings;
// "theme" | "fontSize" | "language"

Indexed access types

You can look up the type of a specific property using the subscript T[K] syntax, where K is a valid key of T.

ts
type PortType = Config["port"]; // number

// Using a union key to get a union of value types
type StringOrBool = Config["host" | "debug"]; // string | boolean

// Getting the element type of an array
const palette = ["red", "green", "blue"] as const;
type Color = typeof palette[number]; // "red" | "green" | "blue"

Combining keyof, typeof, and indexed access lets you write zero-duplication code: define data once as a const, derive all types from it, and let TypeScript keep everything in sync automatically.

Ready to test yourself?
Practice TypeScript— quiz & coding exercises