Загрузка…
Загрузка…
TypeScript · middle · сложность 5
// ✅ 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
}
}Предпочитайте union literals / as const; enum emit JS и reverse-map; widening ломает narrowing.