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.
Code
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: trueWhat 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.