Codectionary / Developer documentation / TypeScript

Deriving Types from Values with typeof

In a type position, typeof refers to the static type of a variable or property. This avoids duplicating the shape of a configuration or factory value. It is separate from JavaScript’s runtime typeof expression, which returns strings such as object or number.

Syntax

const defaults = { retries: 3 };
type Options = typeof defaults;

Examples

Deriving Types from Values with typeof: working example

Run this standalone example after compiling with TypeScript 5.4+ in strict mode, targeting ES2022. Expected result: The program prints queue: 5 and object.

const defaults = { retries: 3, label: "worker" };
type Options = typeof defaults;
function describe(options: Options): string {
  return `${options.label}: ${options.retries}`;
}
console.log(describe({ retries: 5, label: "queue" }));
console.log(typeof defaults);
  1. Expected result: The program prints queue: 5 and object.
  2. Options is a compile-time object shape derived from defaults.
  3. The final typeof executes at runtime and returns a string, not a TypeScript type.

Best practices

  • Use named aliases for repeatedly reused derived shapes.
  • Use const assertions only when literal values should remain narrow.

Runtime & versions

Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

TypeScript Handbook

Specifications & further reading