Загрузка…
Загрузка…
TypeScript · middle · сложность 5
// any — contagious, unsafe, silent
const a: any = JSON.parse('{}');
a.foo.bar.baz(); // ✅ compiles, ❌ crashes — no checking at all
const n: number = a; // any flows into number with no error
// unknown — safe top type; must narrow before use
const u: unknown = JSON.parse('{}');
// u.foo; // ❌ Error: object is of type 'unknown'
if (typeof u === 'object' && u && 'foo' in u) {
(u as { foo: unknown }).foo; // ✅ only after narrowing
}
// never — the bottom type
function fail(msg: string): never { throw new Error(msg); } // never returns
type T = string | never; // = string (never disappears from unions)
// never powers exhaustiveness
type Dir = 'up' | 'down';
function move(d: Dir) {
switch (d) {
case 'up': return 1;
case 'down': return -1;
default: const _: never = d; return _; // errors if a new Dir is added
}
}// catch clauses are `unknown` (with useUnknownInCatchVariables/strict) — not `any`
try { /* ... */ } catch (e) {
// e.message; // ❌ e is unknown
if (e instanceof Error) console.log(e.message); // ✅ narrow first
}any infects; unknown forces proof; never exhausts and vanishes from unions; catch → unknown under strict.