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.
Code
// 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
trueHow 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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.