Загрузка…
Загрузка…
TypeScript · middle · сложность 5
Literal type сужает примитив до одного точного значения ('GET', 200, true); union литералов — идиоматичный «enum». Ключевое слово enum генерирует runtime-объекты с сюрпризами (reverse mapping, не стирается) — чаще предпочитают union literals или объекты as const, если не нужен именно runtime enum.
'success' как тип — не любой string, а ровно эта строка. Unions литералов отлично работают с discriminated unions и autocomplete.
enum / const enum — отдельная runtime-семантика. Numeric enums имеют reverse mapping; string enums — нет. as const на объекте даёт readonly literal types без enum-ключевого слова.
Widening: let x = 'a' → string; const x = 'a' → 'a'. Для discriminant'ов это критично.
// ✅ Union of literals — the default. Zero runtime, JSON-friendly.
type Method = 'GET' | 'POST' | 'PUT' | 'DELETE';
function request(m: Method, url: string) {/* ... */}
request('GET', '/x'); // autocompletes, narrows
// request('get', '/x'); // ❌ Error: 'get' not assignable to Method
// ✅ as const object — when you also need the runtime values
const Status = { Active: 'active', Banned: 'banned' } as const;
type Status = typeof Status[keyof typeof Status]; // 'active' | 'banned'
Object.values(Status); // real array at runtime
// ⚠️ enum keyword — emits runtime code, reverse-maps numbers
enum Color { Red, Green } // { Red:0, Green:1, 0:'Red', 1:'Green' }
Color[0]; // 'Red' — reverse mapping, extra output
// Widening trap
const a = 'GET'; // type 'GET'
let b = 'GET'; // type string (widened)
const o = { m: 'GET' }; // { m: string } — property widened
const o2 = { m: 'GET' } as const; // { readonly m: 'GET' }// Exhaustiveness: unions + never catch missing cases at compile time
function label(s: Status) {
switch (s) {
case 'active': return 'On';
case 'banned': return 'Off';
default: { const _x: never = s; return _x; } // ❌ compile error if a case is unhandled
}
}Литеральные unions и as const — основной инструмент; enum — когда осознанно нужен runtime-объект со всеми его особенностями.