TypeScript is not Java with different syntax. It is JavaScript with a static, structural type system. The runtime, data boundaries and failure modes still matter.
This is a reference for building and maintaining production applications, not a beginner tutorial or a ranking of libraries.
1. The 2026 baseline
TypeScript 6.0 is a transition toward the native compiler architecture. Read its migration notes before upgrading. The important everyday changes are a modern ESM ecosystem, explicit type imports, faster tooling and native TypeScript execution in recent Node.js releases.
Use a supported Node.js LTS release for production. Node 24.12+ supports stable type stripping, but executing TypeScript is not type-checking it.
node src/main.ts
npx tsc --noEmit
For fuller syntax support, use tsx or a compilation pipeline. Native stripping does not implement tsconfig aliases, JSX, runtime enums or parameter properties. NestJS's typical decorator-based setup needs its own compilation pipeline.
A baseline for an ESM application running directly on modern Node:
{
"compilerOptions": {
"target": "ESNext",
"module": "NodeNext",
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"verbatimModuleSyntax": true,
"erasableSyntaxOnly": true,
"rewriteRelativeImportExtensions": true,
"noEmit": true,
"types": ["node"]
}
}
Set "type": "module" in package.json, install @types/node, and use explicit relative file extensions. For a bundled frontend or a compiled library, use a configuration appropriate to that build instead.
2. The type system worth mastering
| Feature | Use it for |
|---|---|
unknown |
Untrusted input and caught exceptions |
never |
Exhaustiveness and impossible states |
satisfies |
Checking shape while preserving inference |
as const |
Literal values and readonly tuples |
| Generics | Preserving relationships between types |
keyof, indexed access |
Type-safe property access |
| Mapped types | Deriving related shapes |
Conditional types, infer
|
Extracting or transforming types |
Pick, Omit, Record
|
Small, focused derived contracts |
Awaited, ReturnType
|
Deriving async and function results |
Model states, not optional properties
type Job =
| { status: 'pending' }
| { status: 'running'; startedAt: Date }
| { status: 'done'; resultId: string }
| { status: 'failed'; reason: string };
function assertNever(value: never): never {
throw new Error(`Unexpected state: ${String(value)}`);
}
function describe(job: Job): string {
switch (job.status) {
case 'pending': return 'Waiting';
case 'running': return 'Working';
case 'done': return job.resultId;
case 'failed': return job.reason;
default: return assertNever(job);
}
}
Adding a new state now forces consumers to handle it. A union describes valid states; a transition function must still enforce valid transitions.
Preserve inference
const limits = {
search: 5,
export: 2,
} as const satisfies Record<string, number>;
type Operation = keyof typeof limits;
Generics that express a relationship
function get<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
Use interfaces for extensible object contracts, type aliases for unions and transformations. Neither provides runtime validation. Avoid clever type gymnastics when a simpler contract works.
3. Validate data at the boundary
A type assertion is not validation. JSON.parse, HTTP responses, queue messages and environment variables can contain anything.
import { z } from 'zod';
const CreateJob = z.object({
candidateId: z.uuid(),
priority: z.enum(['normal', 'high']),
});
type CreateJob = z.infer<typeof CreateJob>;
function decode(input: unknown): CreateJob {
return CreateJob.parse(input);
}
This example uses Zod 4. Use safeParse when invalid input is an expected outcome. Keep transport schemas separate from domain entities when their lifecycles differ. Validate configuration once at startup.
colinhacks
/
zod
TypeScript-first schema validation with static type inference
Zod
TypeScript-first schema validation with static type inference
by @colinhacks
What is Zod?
Zod is a TypeScript-first validation library. Define a schema and parse some data with it. You'll get back a strongly typed, validated result.
import * as z from "zod";
const User = z.object({
name: z.string(),
});
// some untrusted data...
const input = {
/* stuff */
};
// the parsed result is validated and type safe!
const data = User.parse(input);
// so you can use it with confidence :)
console.log(data.name);
Features
- Zero external dependencies
- Works in Node.js and all modern browsers
- Tiny:
2kbcore bundle (gzipped) - Immutable API: methods return a new instance
- Concise interface
- Works with…
4. Errors are part of the contract
Use exceptions for unexpected infrastructure failures and explicit results for expected business outcomes.
type Result<T, E> =
| { ok: true; value: T }
| { ok: false; error: E };
type CreateError = 'duplicate' | 'not_allowed';
type CreatedJob = Result<{ id: string }, CreateError>;
Map domain errors to HTTP responses at the transport layer. Do not swallow errors, log sensitive payloads, or expose internal stack traces to clients.
5. Node.js: understand the runtime
| Concept | Production implication |
|---|---|
| Event loop | CPU-heavy synchronous work delays other requests |
| Promises | Concurrent I/O is not CPU parallelism |
| Worker threads | Isolate expensive CPU work |
| Streams | Process large inputs with bounded memory |
| Backpressure | Slow producers when consumers cannot keep up |
| AbortSignal | Propagate cancellation and deadlines |
| AsyncLocalStorage | Carry request context through async calls |
Timeouts and cancellation
const response = await fetch(url, {
signal: AbortSignal.timeout(5_000),
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
A timeout does not guarantee the remote operation was rolled back. Retry only when the operation is safe or protected by an idempotency mechanism.
Bounded concurrency
import pLimit from 'p-limit';
const limit = pLimit(8);
const results = await Promise.allSettled(
ids.map(id => limit(() => fetchRecord(id)))
);
For millions of inputs, consume batches or streams instead of allocating millions of queued promises. Promise.all rejects early but does not cancel the other tasks.
import { pipeline } from 'node:stream/promises';
import { createReadStream, createWriteStream } from 'node:fs';
import { createGzip } from 'node:zlib';
await pipeline(
createReadStream('records.jsonl'),
createGzip(),
createWriteStream('records.jsonl.gz')
);
6. Backend architecture: choose boundaries before frameworks
HTTP / Queue / CLI
|
Use cases
|
Domain + ports
|
Adapter implementations
SQL / APIs / messaging
Organize by feature or bounded context. Keep business rules independent of HTTP handlers and database implementation details. Prefer a modular monolith until independent deployment or scaling justifies distribution.
interface JobRepository {
insert(job: { id: string }): Promise<void>;
}
function createJob(repo: JobRepository) {
return async (id: string) => {
await repo.insert({ id });
return { id };
};
}
Dependency injection does not require a container. Use one when lifecycle management and composition justify it. Interfaces disappear at runtime; frameworks such as NestJS require runtime injection tokens for interface-based dependencies.
| Pattern | When it pays off |
|---|---|
| Adapter | Isolate external services |
| Strategy | Select interchangeable business policies |
| Repository | Encapsulate meaningful persistence operations |
| State machine | Enforce workflow transitions |
| Transactional outbox | Commit business changes and pending events together |
| Idempotent consumer | Handle duplicated deliveries safely |
| Saga | Coordinate long-running, compensatable operations |
| Circuit breaker | Contain repeated upstream failures |
| CQRS | Distinct read/write needs justify added complexity |
An outbox is not exactly-once delivery: consumers still need deduplication. Use database unique constraints and atomic operations rather than in-memory flags for cross-process correctness.
7. Durable workflows
For operations spanning hours, services or human approvals, consider Temporal instead of hand-rolling timers and retry state.
import { proxyActivities } from '@temporalio/workflow';
import type * as activities from './activities.js';
const { collectRecords, buildReport } = proxyActivities<typeof activities>({
startToCloseTimeout: '2 minutes',
retry: { maximumAttempts: 5 },
});
export async function screening(id: string) {
const records = await collectRecords(id);
return buildReport(records);
}
Workflow code must remain deterministic for replay. Put network calls, database writes and other external effects in activities; make those activities idempotent. Plan for workflow versioning. A simple queue such as BullMQ may be enough for short background jobs.
temporalio
/
sdk-typescript
Temporal TypeScript SDK
Temporal is a distributed, scalable, durable, and highly available orchestration engine used to execute asynchronous, long-running business logic in a scalable and resilient way.
Temporal TypeScript SDK is the framework for authoring workflows and activities using either the TypeScript or JavaScript programming languages.
For documentation and samples, see:
- TypeScript Development Guide
- TypeScript Samples
- TypeScript API Reference
- General Temporal Documentation
Quick Start
Installation
To add Temporal TypeScript SDK packages to an existing JavaScript project, run:
(for client-level features, e.g. starting or interracting with Workflows)
# Or `pnpm add` or `yarn add`
npm install --save \
@temporalio/client \
@temporalio/common
(for worker-level features, including running Workflows, Activities and Nexus Operations)
# Or `pnpm add` or `yarn add`
npm install --save \
@temporalio/worker \
@temporalio/workflow \
@temporalio/activity \
@temporalio/common
All @temporalio/* packages in a project must have the same version number
This requirement is generally enforced by peer dependencies of the Temporal packages
but…
8. React: separate kinds of state
| State | Typical approach |
|---|---|
| Local UI |
useState, useReducer
|
| Remote data | TanStack Query or framework data loaders |
| URL state | Router search parameters |
| Forms | Native forms or React Hook Form + Zod |
| Shared client state | Context, Zustand or Redux Toolkit |
const jobs = useQuery({
queryKey: ['jobs', candidateId],
queryFn: ({ signal }) => fetchJobs(candidateId, signal),
enabled: Boolean(candidateId),
});
Invalidate affected queries after mutations. Distinguish loading, background fetching, empty and error states. Do not mirror server data into local state without a reason.
Know React 19 Actions, useActionState, useOptimistic and Suspense. Server Components depend on framework support; they are not a drop-in feature of every client application. Effects synchronize with external systems; derive ordinary values during render rather than through effects.
TanStack
/
query
🤖 Powerful asynchronous state management, server-state utilities and data fetching for the web. TS/JS, React Query, Solid Query, Svelte Query and Vue Query.
TanStack Query
An async state management library built to simplify fetching, caching, synchronizing, and updating server state.
- Protocol‑agnostic fetching (REST, GraphQL, promises, etc.)
- Caching, refetching, pagination & infinite scroll
- Mutations, dependent queries & background updates
- Prefetching, cancellation & React Suspense support
Get Involved
- We welcome issues and pull requests!
- Participate in GitHub discussions
- Chat with the community on Discord
- See CONTRIBUTING.md for setup instructions
Partners
We're looking for TanStack Query Partners to join our mission! Partner with us to push the boundaries of TanStack Query and build amazing things together.
LET'S CHATExplore the TanStack Ecosystem
- TanStack Config – Tooling for JS/TS packages
- TanStack DB – Reactive sync client store
- TanStack DevTools – Unified devtools panel
- TanStack Form – Type‑safe form state
- TanStack Pacer – Debouncing, throttling, batching
- TanStack Query – Async state & caching
- TanStack Ranger – Range & slider primitives
- TanStack…
9. The ecosystem: a shortlist, not a shopping list
| Need | Options | Decision rule |
|---|---|---|
| HTTP API | Fastify, Hono, Express | Lightweight services and existing ecosystem |
| Structured backend | NestJS | Modules, DI and consistent conventions |
| Runtime schemas | Zod, Valibot | Validate external data |
| Data access | Prisma, Drizzle, Kysely | ORM convenience vs SQL control |
| Messaging | KafkaJS, BullMQ | Event log vs job queue |
| Durable workflows | Temporal | Persistent orchestration |
| Frontend | React, Next.js, Vite | Match rendering and deployment needs |
| API contracts | OpenAPI, tRPC | Cross-language compatibility vs TS-first integration |
| Testing | Vitest, node:test, Jest | Runtime and existing codebase fit |
| Integration/E2E | Testcontainers, MSW, Playwright | Real infrastructure and network behavior |
| Logging/tracing | Pino, OpenTelemetry | Structured logs and distributed correlation |
| Tooling | pnpm, Biome, ESLint | Consistent reproducible builds |
| Monorepos | Nx, Turborepo | Use when multiple packages merit orchestration |
Do not introduce a library merely because it is on this table. Check its maintenance, compatibility, security and operational costs.
10. Testing and delivery
import { describe, it, expect } from 'vitest';
describe('CreateJob schema', () => {
it('rejects an invalid candidate ID', () => {
expect(CreateJob.safeParse({
candidateId: 'invalid', priority: 'normal'
}).success).toBe(false);
});
});
Import CreateJob from its schema module in a real test. Test domain rules with unit tests, database constraints using real databases, external contracts at integration boundaries, and critical user journeys with Playwright. Include retries, duplicate events, timeouts and concurrency failures.
CI should perform independent checks:
pnpm install --frozen-lockfile
pnpm exec tsc --noEmit
pnpm exec vitest run
pnpm exec eslint .
Adapt these commands to the project's installed dependencies. Transpilation and successful tests do not automatically guarantee type correctness.
vitest-dev
/
vitest
Next generation testing framework powered by Vite.
Vitest
Next generation testing framework powered by Vite
Documentation | Getting Started | Examples | Why Vitest?
Features
- Vite's config, transformers, resolvers, and plugins. Use the same setup from your app!
- Jest Snapshot
- Chai built-in for assertions, with Jest expect compatible APIs
- Smart & instant watch mode, like HMR for tests!
-
Native code coverage via
v8oristanbul. - Jest-compatible mocking, stubbing, and spies.
- JSDOM and happy-dom for DOM and browser API mocking
- Browser Mode for running component tests in the browser
- Components testing (Vue, React, Svelte, Lit, Marko)
- Benchmarking support with Tinybench
- Projects support
- expect-type for type-level testing
- ESM first, top level await
- Out-of-box TypeScript / JSX support
- Filtering, timeouts, concurrent for suite and tests
- Sharding support
- Reporting Uncaught Errors
- Run your tests in the browser natively
Vitest requires Vite >=v6.4.0 and Node >=v22.12.0
import { assert,…11. Production checklist
- Strict types; no unexamined
any, assertions or non-null operators. - Runtime validation at trust boundaries.
- Explicit timeouts, bounded retries with jitter, bounded concurrency.
- Database constraints, transactional boundaries and idempotency.
- Structured logs, correlation IDs, metrics and traces; redact personal data.
- Authorization at the resource level, parameterized SQL, secure secrets management.
- Graceful shutdown: stop accepting work, drain in-flight tasks, close resources.
- Test real failure modes, not just happy paths.
- Review generated code just like handwritten code; require tests and type checks.
References
- TypeScript handbook
- TypeScript 6.0 release notes
- Node.js TypeScript support
- Zod documentation
- React documentation
- TanStack Query
- Temporal TypeScript SDK
- DEV editor guide
The goal is not to know every TypeScript feature. It is to make invalid states harder to represent, failures easier to recover from, and systems easier to change.


Top comments (0)