π·
EPISODE 02
type Β· any Β· unknown Β· never Β· narrowing
Type Aliases & any/unknown/never
Name complex types with type aliases, understand any (escape hatch), unknown (safe any), and never (impossible). Learn type narrowing.
typeanyunknownnevernarrowing
Duration
β± About 1.5 hours
Level
π Intermediate
Prerequisite
π― ts-01
OUTCOME
Choose the right escape hatch and narrow types correctly
What you'll learn
- 1Define type aliases for object and union types
- 2Distinguish any from unknown
- 3Use never for exhaustive switch checks
- 4Narrow with typeof, in, and discriminated unions
1. Type Aliases
typescript
type User = {
id: number;
name: string;
email?: string; // optional
readonly createdAt: Date;
};
const u: User = { id: 1, name: "Alice", createdAt: new Date() };2. any vs unknown
typescript
// any: turn off type checking (use sparingly)
let a: any = JSON.parse(text);
a.whatever.does.not.error;
// unknown: safe β you must narrow before using
let u: unknown = JSON.parse(text);
if (typeof u === "object" && u !== null && "name" in u) {
console.log((u as { name: string }).name);
}π‘
Reach for unknown when you must, any almost never. unknown forces you to validate before use.
3. never & Exhaustive Checks
typescript
type Shape = { kind: "circle"; r: number } | { kind: "square"; side: number };
function area(s: Shape): number {
switch (s.kind) {
case "circle": return Math.PI * s.r ** 2;
case "square": return s.side ** 2;
default: {
const _exhaustive: never = s; // compile error if a case is missed
return _exhaustive;
}
}
}4. Narrowing
typescript
function describe(value: string | number) {
if (typeof value === "string") {
return value.toUpperCase();
}
return value.toFixed(2);
}
function take(item: { kind: "a"; x: number } | { kind: "b"; y: string }) {
if (item.kind === "a") item.x; // narrowed to first variant
else item.y; // narrowed to second
}Example code / lecture materials
All lecture materials and example code are openly available on GitHub.
View on GitHub β