typeof Operator Derives Types From Values

The typeof type operator turns a runtime constant's full shape into a type, so nested config fields keep literal types without hand-writing an interface.

TypescriptConfig Management

Code

typescriptsnippet
18 lines
const DEFAULT_CONFIG = {
  port: 8080,
  host: 'localhost',
  retries: { max: 3, backoffMs: 250 },
} as const;

// The typeof type operator lifts the value's shape into the type system
type AppConfig = typeof DEFAULT_CONFIG;

function describe(config: AppConfig): string {
  return config.host + ':' + config.port + ' retries<=' + config.retries.max;
}

console.log(describe(DEFAULT_CONFIG));

// AppConfig carries literal types from the value: port is 8080, not number
const portCheck: 8080 = DEFAULT_CONFIG.port;
console.log('literal type holds:', portCheck === 8080);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

localhost:8080 retries<=3
literal type holds: true

What the snippet does

Structurally, expect the function describe and nothing else.

What to watch for

  • Every symbol it touches is built into the language — nothing needs fetching.

Applying it

Entry signature: function describe(config: AppConfig)

Each run prints the 1 labeled block literal type holds: in source order.

Statements that matter

return config.host + ':' + config.port + ' retries<=' + config.retries.max;

Interactive Tools for This Topic

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `describe` at load time.