Skip to content

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.

“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.”

let name: string = 'Ada';
let age: number = 36; // no separate int/float
const scores: number[] = [1, 2, 3];
let pair: [string, number] = ['age', 36]; // tuple: fixed length and order
let safe: unknown; // holds anything, must narrow before use
let empty: never; // the empty set — unreachable code

never 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.

type Status = 'idle' | 'loading' | 'success' | 'error'; // union: one of
type Entity = { id: string } & { createdAt: Date }; // intersection: both

Unions 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.

narrowing.ts
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 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.

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.ts
type Role = 'admin' | 'editor' | 'viewer';
interface User { id: string; name: string; email: string; role: Role }
type PartialUser = Partial<User>; // all optional
type NameOnly = Pick<User, 'id' | 'name'>; // subset
type NoEmail = Omit<User, 'email'>; // complement
type ByRole = Record<Role, User[]>; // keys -> values
type NonNullRole = NonNullable<Role | null>;
type Fn = (u: User) => Promise<void>;
type Args = Parameters<Fn>; // [u: User]
type Settled = Awaited<ReturnType<Fn>>; // void

Exclude<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 checks a value against a type without widening it. An annotation replaces the inferred type; satisfies keeps it.

satisfies.ts
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 signature

With : Record<string, Route> the variable would accept any key and lose the literal types. Use satisfies for config objects, lookup tables and constant maps.

  1. Why is { a: string } & { a: number } effectively never?
  2. When does narrowing not work, and why?
  3. What does readonly actually prevent?
  4. How do you type an object whose keys are known only at runtime?
  • Using any to fix an error. It hides the next ten errors too.
  • Thinking as performs a conversion. Nothing is checked or changed at runtime.
  • Mutating a readonly array through a non-readonly alias. readonly is shallow and compile-time only.
  • Confusing never with void. never has no values; void functions do return.
  • Assuming interfaces are closed. Declaration merging means another file can add fields.