String Unions and Autocomplete
Get editor autocomplete for known string values.
Unions Drive Autocomplete
A union of string literals does double duty: it restricts allowed values and feeds your editor's autocomplete. But sometimes you want suggestions and the freedom to pass any string — a clever trick handles that.
A Basic String Literal Union
Declare a union of allowed strings. The editor offers exactly these options, and invalid values are compile errors.
type Variant = "primary" | "secondary" | "danger"
const v: Variant = "primary"
console.log(v)
// const bad: Variant = "warning" // ErrorAll lessons in this course
- Template Literal Type Basics
- Modeling Structured Strings
- String Unions and Autocomplete
- Intrinsic String Manipulation Types