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);- Expected result: The program prints queue: 5 and object.
- Options is a compile-time object shape derived from defaults.
- 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