0Pricing
TypeScript Academy · Lesson

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" // Error

All lessons in this course

  1. Template Literal Type Basics
  2. Modeling Structured Strings
  3. String Unions and Autocomplete
  4. Intrinsic String Manipulation Types
← Back to TypeScript Academy