Skip to main content
Практика завдань

Літеральні типи в TypeScript

Що таке Літеральні Типи?

Літеральні типи дозволяють вам вказати точне значення, яке може містити змінна — не просто тип, як string або number, а конкретний рядок, число або булеве значення.


Літеральні Типи Рядків

typescript
type Direction = "up" | "down" | "left" | "right"; function move(dir: Direction) { console.log(`Moving ${dir}`); } move("up"); // ✅ move("left"); // ✅ move("diagonal"); // ❌ Помилка

Літеральні Числові Типи

typescript
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6; function roll(): DiceRoll { return Math.ceil(Math.random() * 6) as DiceRoll; } type HttpSuccessCode = 200 | 201 | 204; type HttpErrorCode = 400 | 401 | 403 | 404 | 500; type HttpStatusCode = HttpSuccessCode | HttpErrorCode;

Літеральні Булеві Типи

typescript
type True = true; type False = false; type IsLoading = true | false; // Те ж саме, що і boolean

Заява as const

as const робить значення літеральними та тільки для читання:

typescript
// Без as const — розширено до string[] const colors = ["red", "green", "blue"]; // тип: string[] // З as const — звужено до тільки для читання кортежу літералів const colors = ["red", "green", "blue"] as const; // тип: readonly ["red", "green", "blue"] type Color = typeof colors[number]; // "red" | "green" | "blue"

Об'єкт з as const

typescript
const config = { api: "https://api.example.com", timeout: 5000, retries: 3 } as const; // тип: { readonly api: "https://api.example.com"; readonly timeout: 5000; readonly retries: 3 } type ApiUrl = typeof config.api; // "https://api.example.com" (літерал, не string)

Практичні Використання

Обробка Подій

typescript
type EventType = "click" | "focus" | "blur" | "submit"; function addEventListener(event: EventType, handler: () => void) { // ... }

Опції Налаштування

typescript
type LogLevel = "debug" | "info" | "warn" | "error"; type Theme = "light" | "dark" | "system"; type Size = "sm" | "md" | "lg" | "xl"; interface ButtonProps { size: Size; variant: "primary" | "secondary" | "outline" | "ghost"; disabled?: boolean; }

Дискриміновані Об'єднання

typescript
type Shape = | { kind: "circle"; radius: number } | { kind: "rect"; width: number; height: number } | { kind: "triangle"; base: number; height: number }; function area(shape: Shape): number { switch (shape.kind) { case "circle": return Math.PI * shape.radius ** 2; case "rect": return shape.width * shape.height; case "triangle": return 0.5 * shape.base * shape.height; } }

Літеральні Типи Шаблонів

Поєднуйте літеральні типи з шаблонними рядками:

typescript
type Color = "red" | "blue" | "green"; type Shade = "light" | "dark"; type ColorVariant = `${Shade}-${Color}`; // "light-red" | "light-blue" | "light-green" | "dark-red" | "dark-blue" | "dark-green"

Важливо:

Літеральні типи забезпечують безпеку, подібну до enum, без фактичних enum. У поєднанні з об'єднаними типами та as const, вони забезпечують відмінну типову безпеку для налаштувань, обробки подій та управління станом. У більшості випадків надавайте перевагу літеральним об'єднанням замість enum.

Коротка відповідь

Для співбесіди
Premium

Коротка відповідь допоможе вам впевнено відповідати на цю тему під час співбесіди.

Дочитали статтю?
Практика завдань