Unions Stay Open With string Ampersand Braces

Intersecting string with an empty object type keeps literal autocomplete while still accepting any runtime string — a plain union cannot do both.

TypescriptForm Validation

Code

typescriptsnippet
18 lines
// string & {} keeps literal completions while still accepting any string
type Theme = 'light' | 'dark' | 'high-contrast' | (string & {});

function applyTheme(theme: Theme): string {
  return `theme=${theme}`;
}

console.log(applyTheme('dark')); // literal: suggested and checked
console.log(applyTheme('sepia')); // arbitrary string: still accepted

// A plain union would reject unknown strings at compile time
type StrictTheme = 'light' | 'dark' | 'high-contrast';

// const s: StrictTheme = 'sepia'; // error TS2322: not assignable

const themes: Theme[] = ['dark', 'sepia', 'light'];
console.log(themes.join(', '));
console.log(applyTheme(themes[1] as StrictTheme) === 'theme=sepia');

Output

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

theme=dark
theme=sepia
dark, sepia, light
true

How it works

Unions Stay Open With string Ampersand Braces comes down to the function applyTheme.

Watch out for

  • Any imports it has point exclusively at standard-library modules.

Applying it

Signature: function applyTheme(theme: Theme)

Statements that matter

return `theme=${theme}`;

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library. The file defines `applyTheme` at load time.