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.

TypescriptConfig Management

Code

typescriptsnippet
30 lines
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 pro

Tracing 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

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.