Const Keeps Literals While Let Widens
const preserves literal types but let widens them to string, so union-typed parameters reject the widened value until an annotation stops the widening.
Code
type Mode = 'readonly' | 'edit';
function openIn(mode: Mode): string {
return `opened in ${mode} mode`;
}
// const preserves the literal type: mode is 'readonly', not string
const mode = 'readonly';
console.log(openIn(mode));
// let widens the literal to string, so it no longer fits Mode
let label = 'edit';
console.log(label);
// openIn(label); // string is not assignable to 'readonly' | 'edit'
// Annotating the declaration stops the widening at the source
let state: 'draft' | 'published' = 'draft';
state = 'published';
console.log(state);
// Object properties widen too; an explicit union type keeps them usable
const flags = { theme: 'dark' as 'dark' | 'light' };
flags.theme = 'light';
console.log(flags.theme);
// as const freezes every property at its literal instead
const frozen = { region: 'eu', tier: 'pro' } as const;
type Region = (typeof frozen)['region']; // 'eu'
type _Region = Region;
console.log(frozen.region, frozen.tier);Output
Captured from a sandboxed run of this snippet in the build pipeline.
opened in readonly mode
edit
published
light
eu proTracing the logic
Const Keeps Literals While Let Widens is built around the function openIn.
Watch out for
- Self-sufficient — the runtime already provides whatever it imports.
Putting it to use
The entry-point signature is function openIn(mode: Mode)
Core lines
const frozen = { region: 'eu', tier: 'pro' } as const;
return `opened in ${mode} mode`;
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
- Are there any imports to resolve outside the language?
- No. Every import resolves against the language's own modules. The file defines `openIn` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.