TypeScript Course
TypeScript
/
Advanced

typeof Operator (in Types)

Definition

In the type context, `typeof` takes a JavaScript variable or object and generates a TypeScript Type based on its shape.

Explain Like I'm New

Usually, you write the Type first (the blueprint), and then build the Object (the house). But sometimes, you already have the Object, and you want to auto-generate the blueprint from it. `typeof` points a scanner at a JS variable and extracts its shape into a TS Type.

Real World Example

You have a massive, deeply nested configuration object `const config = { theme: 'dark', api: { url: '...' } }`. Instead of writing out a 50-line interface manually, you just do `type ConfigType = typeof config;`.

Common Use Cases

  • •Extracting types from JSON objects
  • •Extracting the signature of an existing function

Interactive Example

// A plain JavaScript object (No interface exists!)
const defaultSettings = {
  volume: 80,
  graphics: "high",
  fullscreen: true
};

// Auto-magically extract the blueprint into a TypeScript Type
type SettingsType = typeof defaultSettings;

/* SettingsType is equivalent to:
  {
    volume: number;
    graphics: string;
    fullscreen: boolean;
  }
*/

// Ensure a new variable matches the shape of the default settings
const userSettings: SettingsType = {
  volume: 50,
  graphics: "low",
  fullscreen: false
};

Interview Questions

basic

  • What is the difference between JS `typeof` and TS `typeof`?

intermediate

  • Can you use TS `typeof` on a function to get its signature?

advanced

  • How do you combine `typeof` and `keyof`?

Flash Cards

Question

JS vs TS typeof?

Click to reveal answer
Answer

JS `typeof` runs at runtime and returns a basic string (like `'object'` or `'function'`). TS `typeof` is used exclusively in type annotations (e.g., `type MyType = typeof obj`) and completely vanishes after compilation.

Question

How do you combine them?

Click to reveal answer
Answer

`type Keys = keyof typeof myObject;`. This extracts the blueprint of the object, and then instantly extracts a union of its keys. Incredibly useful for creating enums from plain JS objects.