TypeScript Types
The TypeScript type system is a small language of its own, built from a handful of combinators. Most “advanced” types are compositions of unions, intersections, indexed access and conditional types. Learn the primitives and the combinators separately, and the rest stops looking magical.
The 60-second answer
Section titled “The 60-second answer”“Types are sets of values. string is the set of all strings; 'a' | 'b' is a two-element set;
A & B is the intersection of two sets, so it requires both shapes. Narrowing shrinks a set inside a
branch — typeof, in, instanceof, truthiness, or a discriminant field. unknown is the safe top
type: it holds anything but must be narrowed before use, whereas any turns checking off and spreads.
Interfaces and type aliases describe shapes almost interchangeably, except that types express unions
and mapped types, and interfaces can merge declarations. Utility types are library-defined mapped and
conditional types.”
Primitives, literals, arrays
Section titled “Primitives, literals, arrays”let name: string = 'Ada';let age: number = 36; // no separate int/floatconst scores: number[] = [1, 2, 3];let pair: [string, number] = ['age', 36]; // tuple: fixed length and orderlet safe: unknown; // holds anything, must narrow before uselet empty: never; // the empty set — unreachable codenever is the return type of a function that always throws, and the exhaustiveness check in a
switch. void is different — a function that returns undefined, whose result callers may ignore.
any opts out of checking entirely and spreads through everything it touches. Literal types
('admin', 42) are singleton sets and the basis of unions:
const ROLES = ['admin', 'editor', 'viewer'] as const;type Role = (typeof ROLES)[number]; // 'admin' | 'editor' | 'viewer'as const turns a literal into a readonly tuple of literal types — an enum-like union without an
enum, which is why many teams avoid enum entirely.
Unions, intersections and narrowing
Section titled “Unions, intersections and narrowing”type Status = 'idle' | 'loading' | 'success' | 'error'; // union: one oftype Entity = { id: string } & { createdAt: Date }; // intersection: bothUnions only expose properties common to all members until you narrow. Intersections combine, and
conflicting property types collapse to never, which is why { a: string } & { a: number } is
uninhabited and almost always a bug.
type Shape = | { kind: 'circle'; radius: number } | { kind: 'square'; side: number };
function area(shape: Shape): number { switch (shape.kind) { case 'circle': return Math.PI * shape.radius ** 2; case 'square': return shape.side ** 2; default: return assertNever(shape); }}
function isUser(value: unknown): value is User { return typeof value === 'object' && value !== null && 'id' in value;}(User here is any { id: string }-shaped interface, such as interface User { id: string; name: string }.)
Narrowing tools: typeof for primitives, instanceof for classes, in for key presence, truthiness
for null/undefined, equality against literals, and user-defined guards. A guard is an unchecked
promise — if the body is wrong, the compiler still believes you. Validation libraries (Zod, Valibot)
generate the runtime check and the type together, which is the honest version of the same idea.
interface versus type
Section titled “interface versus type”interface |
type |
|
|---|---|---|
| Object shapes | Yes | Yes |
| Unions | No | Yes |
| Mapped types | No | Yes |
| Declaration merging | Yes | No |
| Error messages | Often clearer | Sometimes noisier |
Default to interface for object shapes others may extend, and type for everything else. The rule:
type when you need a union, tuple or mapped type; interface when you are describing a contract
that could be augmented.
unknown versus any
Section titled “unknown versus any”function unsafe(input: any) { input.whatever(); } // no error, crashes at runtime
function safe(input: unknown) { if (typeof input === 'string') return input.toUpperCase(); // input.whatever(); // error — must narrow first}any is contagious: it flows through every operation and silences the rest of the chain. unknown
is the correct type for “not validated yet” — JSON.parse, catch-clause variables under
useUnknownInCatchVariables, third-party callback payloads. Prefer unknown at boundaries.
Utility types
Section titled “Utility types”type Role = 'admin' | 'editor' | 'viewer';interface User { id: string; name: string; email: string; role: Role }
type PartialUser = Partial<User>; // all optionaltype NameOnly = Pick<User, 'id' | 'name'>; // subsettype NoEmail = Omit<User, 'email'>; // complementtype ByRole = Record<Role, User[]>; // keys -> valuestype NonNullRole = NonNullable<Role | null>;type Fn = (u: User) => Promise<void>;type Args = Parameters<Fn>; // [u: User]type Settled = Awaited<ReturnType<Fn>>; // voidExclude<T, U> and Extract<T, U> operate on unions. Awaited<T> unwraps nested promises and is
the one people forget when typing async helpers.
satisfies
Section titled “satisfies”satisfies checks a value against a type without widening it. An annotation replaces the inferred
type; satisfies keeps it.
type Route = { path: string; auth: boolean };
const routes = { home: { path: '/', auth: false }, admin: { path: '/admin', auth: true },} satisfies Record<string, Route>;
routes.admin.path; // string — key set preserved// routes.missing; // error — keys are known, not an index signatureWith : Record<string, Route> the variable would accept any key and lose the literal types. Use
satisfies for config objects, lookup tables and constant maps.
Follow-up questions
Section titled “Follow-up questions”- Why is
{ a: string } & { a: number }effectivelynever? - When does narrowing not work, and why?
- What does
readonlyactually prevent? - How do you type an object whose keys are known only at runtime?
Common traps
Section titled “Common traps”- Using
anyto fix an error. It hides the next ten errors too. - Thinking
asperforms a conversion. Nothing is checked or changed at runtime. - Mutating a
readonlyarray through a non-readonly alias.readonlyis shallow and compile-time only. - Confusing
neverwithvoid.neverhas no values;voidfunctions do return. - Assuming interfaces are closed. Declaration merging means another file can add fields.