What TypeScript Actually Is
TypeScript is a statically typed superset of JavaScript. It adds a type system, compiles to ordinary JavaScript, and exists as a project from Microsoft since 2012 — which is a longer track record than most people assume when they call it a JavaScript trend. The handbook's background chapter explains the design intent, and the rest of it is genuinely readable rather than a reference dump.
Three properties explain almost everything about how it feels to use.
It is structurally typed. Two types are compatible when their members are compatible, regardless of their names. An object with id and name satisfies User without declaring that it is one. That flexibility is why it adopts easily into an existing JavaScript codebase and why it occasionally lets a value be more specific than you intended.
Types are erased. Annotations are checked by the compiler and then removed. There is no runtime type information, no reflection, and no performance cost at runtime — the same reason you cannot write instanceof User for an interface, because an interface does not exist after compilation.
The compiler is also the editor. tsc and tsserver share a single inference engine, so the code you see in autocomplete is the same analysis that fails your build. That is why a typed codebase feels dramatically faster to navigate even before any bug is caught: rename a property and every reference is found instantly.
The practical corollary is that TypeScript catches a class of errors at a different point in time. It does not make code correct. It moves a specific category of mistakes from "3am, in production" to "before the commit".
The Error You Would Otherwise Ship
Here is the bug we see more than any other in untyped JavaScript — a mistyped property name that silently evaluates to undefined:
jsfunction lineTotal(line) { return (line.unitPric * line.quantity) / 100; } const lines = await db.query("select * from order_lines"); const total = lines.reduce((sum, line) => sum + lineTotal(line), 0);
line.unitPric is undefined, so every total becomes NaN. Nothing throws. The order is placed, the customer is charged, and the discrepancy surfaces days later in a reconciliation report. Add the type and the compiler stops the commit:
tstype OrderLine = { unitPriceCents: number; quantity: number }; function lineTotal(line: OrderLine): number { return (line.unitPriceCents * line.quantity) / 100; } const lines = await db.query<OrderLine[]>("select * from order_lines"); const total = lines.reduce((sum, line) => sum + lineTotal(line), 0);
texterror TS2353: Object literal may only specify known properties, and 'unitPric' does not exist in type 'OrderLine'.
The second, and in our experience more valuable, category is shape drift across a boundary:
tstype Order = { id: string; totalCents: number; placedAt: string }; function render(order: Order) { return order.totalCents.toFixed(2); } render({ id: "4521", total_cents: 1250, placed_at: "2025-09-03T10:00:00Z" });
texterror TS2345: Argument of type '{ id: string; total_cents: number; placed_at: string; }' is not assignable to parameter of type 'Order'. Object literal may only specify known properties, but 'total_cents' does not exist in type 'Order'. Did you mean 'totalCents'?
That second error is the compiler doing the job you hired it for: telling you the API and the call site disagree, at compile time, with a suggestion. In a codebase without it, this mismatch becomes a undefined and a .toFixed is not a function in production. Note also that render now cannot be called with undefined, because Order excludes it — which is the second half of the win.
The Constructs That Earn Their Keep
The basics — interfaces, type aliases, unions, inference — are covered in the handbook. These are the ones that reliably change how we write code.
Discriminated unions
One shared field across every member turns a family of related shapes into something the compiler can reason about exhaustively:
tstype PaymentResult = | { status: "succeeded"; captureId: string; amountCents: number } | { status: "failed"; code: string; retryable: boolean } | { status: "pending"; pollAfterMs: number }; function describe(result: PaymentResult): string { switch (result.status) { case "succeeded": return "Captured " + result.captureId; case "failed": return result.code + (result.retryable ? " (retryable)" : " (terminal)"); case "pending": return "Retry in " + result.pollAfterMs + "ms"; default: { const exhaustive: never = result; return exhaustive; } } }
Inside case "failed", result.retryable is not optional — the union has told the compiler which member you are in. And adding a fourth member to PaymentResult makes the default branch fail to compile, because result is no longer assignable to never. The compiler then lists every place that needs updating. That is the property worth paying for: with a single fat interface full of optional fields, adding a state breaks nothing at compile time and shows up as a missing case in production.
satisfies: checking without widening
A type annotation on a const both validates the object and replaces its inferred type. satisfies (TypeScript 4.9+) validates without replacing:
tstype RetryConfig = { retries: number; backoff: "fixed" | "exponential" }; const config = { retries: 3, backoff: "exponential", label: "checkout-call", } satisfies RetryConfig; // Known properties are still checked... const wrong = { retries: 3, backoff: "linear", // error: not assignable to "fixed" | "exponential" } satisfies RetryConfig; // ...and the original inferred type is preserved, so this autocompletes. console.log(config.label.toUpperCase());
Under a plain annotation (const config: RetryConfig = {...}) the extra label property would be checked and then discarded from the variable's type, so config.label would error. With satisfies you get the validation and the precision. The handbook's object types chapter covers it in detail; the short version is that it is the right annotation for configuration objects and lookup tables.
Generics
Generics let a function hold onto the relationship between its input and output, which any cannot and which overloading will not express. A constrained generic, where K must be a key of T:
tsfunction pluck<T, K extends keyof T>(rows: readonly T[], key: K): T[K][] { return rows.map((row) => row[key]); } type Order = { id: string; totalCents: number; status: string }; const totals = pluck<Order, "totalCents">(orders, "totalCents"); // number[] const ids = pluck(orders, "id"); // T inferred, returns string[]
The interesting part is pluck(orders, "id" — no type argument written, and the return type is still string[] rather than any[]. The handbook's generics chapter explains why inference works here: TypeScript solves K from the argument before it needs the return type.
The same idea composes into mapped types, which are how you avoid hand-writing five nearly identical form shapes:
tstype Order = { id: string; totalCents: number; status: string }; // Everything optional, for an edit form before save type Draft<T> = { [K in keyof T]?: T[K] }; const patch: Draft<Order> = { status: "shipped" };
Then there is inference, which is the construct most people underuse. You do not need annotations on local variables — inference usually produces the same type with less noise, and an annotation on every const is noise reviewers have to read past. Annotate function boundaries, exported values and anything the compiler cannot infer. One trap: annotating every binding as const widens the properties of an object literal, which breaks a discriminated union at exactly the point where it was useful.
Strictness Is the Actual Feature
A fresh tsconfig from create-next-app or create-tsconfig is not strict by default. The setting that changes everything is strictNullChecks, and it is off unless you ask:
json{ "compilerOptions": { "target": "ES2022", "lib": ["ES2023", "DOM"], "module": "ESNext", "moduleResolution": "bundler", "strict": true, "noUncheckedIndexedAccess": true, "noImplicitOverride": true, "exactOptionalPropertyTypes": true, "skipLibCheck": true, "noEmit": true }, "include": ["src"] }
strictbundlesnoImplicitAny,strictNullChecks,strictFunctionTypes,strictBindCallApplyand three more. Turning it on is the single highest-value change.noUncheckedIndexedAccessmakesarr[0]of typeT | undefined. Without it, array and record access type-checks asTeven though the element may not exist, which is how "undefined is not an object" survives a type checker. It is noisy at first and correct in the end.exactOptionalPropertyTypesdistinguishes{note?: string}from{note: string | undefined}. Genuinely disruptive; adopt it afterstrict, not before.skipLibCheckstops the compiler checking the type declarations insidenode_modules, which is unrelated to your code and regularly fails on mismatched@typesversions. Every large TypeScript codebase has it on.
If turning on strict feels impossible, scope it per directory and let the compiler hold both worlds:
ts// packages/legacy/tsconfig.json { "extends": "../../tsconfig.base.json", "compilerOptions": { "strictNullChecks": false } }
Strangler migrations work this way — old packages stay permissive, new packages opt in, and the count of remaining errors is a number you can watch fall.
What TypeScript Does Not Fix
The honest list is longer than the marketing, and knowing it is what stops the disappointment.
It does not validate anything at runtime. Types are erased, so a value crossing the network or coming off disk is whatever the sender said it was. This matters enormously for anything that receives input:
ts// Server Action — formData.get() returns FormDataEntryValue | null export async function updateEmail(formData: FormData) { const raw = String(formData.get("email")); await db.query("update users set email = $1 where id = $2", [raw, userId]); // raw is typed. It is not validated. It can be "'; drop table users --". }
JSON.parse returns any on purpose — the browser cannot know the shape — and an any from the network propagates through everything downstream. A runtime parser such as zod at every boundary is the complement to the type system, not a replacement for it.
It does not check business logic. if (order.status !== "paid") return; forgetToRecalculateTotal(order) compiles perfectly. No compiler in the world knows what your tax rules are.
It does not catch concurrency or timing. A floating promise — calling await on nothing, or forgetting await entirely — is not a type error, because Promise<void> is assignable to void. Nor does it see races, and it cannot make a Server Action idempotent.
It does not make things fast. Zero runtime cost, zero runtime benefit. A type error in a .js file is invisible unless you enable checkJs, and the types you write have to be maintained like code.
Where any and Type Assertions Defeat the System
The type system is only as strong as its weakest annotation, and any and as are two doors straight out of it.
ts// any disables checking in both directions, and infects whatever it touches const total: any = await res.json(); // res.json() is any; this hides it const doubled: number = total * 2; // still no error // Assertions perform no checking at all — they are a request to stop asking const amount = value as unknown as Money; // three assertions, zero guarantees
ts// unknown is the fix: everything is assignable to it, nothing escapes it const raw: unknown = await res.json(); if (typeof raw === "object" && raw !== null && "totalCents" in raw) { const cents = raw.totalCents; if (typeof cents === "number") { render(cents); } }
unknown and any are opposites despite looking similar: any is assignable to everything, unknown is only assignable to unknown and any. Narrowing it with typeof, in, or a type guard is how you convert an untrusted value into a trusted one honestly.
Three more ways to quietly opt out:
- The non-null assertion
!.user!.emaildeletes a check the compiler was performing. Ifusercan be null, the check was correct and you have removed it by lying. @ts-expect-error. Unlike@ts-ignore, it fails if there is no error — which is good — but it still stops you fixing the underlying mismatch. Use it on genuinely unfixable third-party types, count them, and make the count fall.as constin the wrong place.as constdeep-freezes a literal for good reasons, and applying it to an API response makes it a lie, because the response is not a compile-time constant.
Two lint rules catch most of this in CI:
json{ "rules": { "@typescript-eslint/no-explicit-any": "error", "@typescript-eslint/no-unsafe-assignment": "warn", "@typescript-eslint/consistent-type-assertions": "error" } }
What to Enforce in CI
bashnpx tsc --noEmit --pretty npx eslint . --max-warnings 0
Run both as required checks. A type error that is not a build failure is a comment in a file, and the value of the whole thing evaporates the first week someone merges with a red build because CI was flaky. Enabling strict on a package you do not own yet is a legitimate way to start — the error count is the migration backlog, and it only goes down.
The short version: TypeScript removes a real and expensive category of mistake — shape and nullability errors at boundaries — and leaves every category that requires domain knowledge exactly where it was. That is a very good trade for a tool with no runtime cost, as long as you keep any rare and pair it with runtime validation at the edges. For where this fits in practice, our web development service covers the build side, Next.js versus React is the framework context, and what SaaS development involves covers the multi-tenant surface where types earn the most. Get in touch if you want a second opinion on a codebase.