
TypeScript is now the default language for serious web development, yet many codebases use it as little more than JavaScript with annotations: any scattered around, API responses cast blindly to interfaces, and payment callbacks trusted without validation. The result is type safety that evaporates exactly where bugs are most expensive. This guide shows how to use TypeScript properly in a modern web application: a strict compiler configuration, types that model your domain, validation at every boundary, and an end-to-end typed API, illustrated with an M-Pesa STK push payment flow.
Key takeaways
- Turn on
strictplus a few extra flags such asnoUncheckedIndexedAccess. The earlier you do it, the cheaper it is. - Model your domain with discriminated unions and branded types so invalid states cannot be represented.
- TypeScript types disappear at runtime. Validate data at boundaries (HTTP requests, webhooks, environment variables, local storage) with a schema library such as zod.
- Define schemas once in a shared package and derive both runtime validation and static types from them, so client and server cannot drift apart.
- Use exhaustive
switchstatements with anevercheck so the compiler tells you when a new state is not handled.
Start with a strict compiler
A strict configuration catches whole classes of bugs before they reach production. For a Node.js API using ES modules, a solid baseline looks like this:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2022"],
"outDir": "dist",
"rootDir": "src",
"strict": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noImplicitOverride": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"useUnknownInCatchVariables": true,
"verbatimModuleSyntax": true,
"isolatedModules": true,
"skipLibCheck": true,
"sourceMap": true
},
"include": ["src"]
}
What the less familiar flags do:
strictenablesstrictNullChecks,noImplicitAny,strictFunctionTypesand related checks. Non-negotiable for new code.noUncheckedIndexedAccessmakesarray[i]andrecord[key]returnT | undefined, forcing you to handle missing values. This prevents a very common class of runtime errors.exactOptionalPropertyTypesdistinguishes "property absent" from "property set toundefined", which matters for PATCH APIs and database updates.verbatimModuleSyntaxrequiresimport typefor type-only imports, making emitted JavaScript predictable for bundlers and Node.useUnknownInCatchVariables(included instrict) types caught errors asunknown, so you must narrow them before use.
With module: "NodeNext" and "type": "module" in package.json, relative imports in source files use the .js extension (for example ./schemas.js), because that is the file Node will load after compilation.
For frontend projects, framework CLIs (Angular, Vite, Next.js) generate their own tsconfig. Keep their module settings, and add the strictness flags above.
Migrating an existing codebase
Turning on every flag at once in a large JavaScript-heavy codebase produces thousands of errors. A practical sequence:
- Enable
strictin a separatetsconfig.strict.jsonthat includes only new or cleaned-up directories. - Add a CI check that counts
anyusages and errors, and only allows the number to go down. - Migrate module by module, starting with code that handles money, authentication and external data.
- Once a directory is clean, move it into the main strict configuration.
Readable, typed code is what keeps a front end maintainable as the team grows.
Model the domain, not just the data
Types should express business rules. Three techniques do most of the work.
Discriminated unions for state
A payment is not "an object with some optional fields". It is in exactly one of several states, each with its own data:
type Payment =
| { status: "pending"; checkoutRequestId: string }
| { status: "succeeded"; receipt: string; amountKes: number; paidAt: string }
| { status: "failed"; reason: string };
The shared literal property status is the discriminant. When you check it, TypeScript narrows the type, so payment.receipt is only accessible after confirming status === "succeeded". A payment that has a receipt but is still "pending" simply cannot be represented.
Exhaustiveness checking
export function assertNever(value: never): never {
throw new Error(`Unhandled case: ${JSON.stringify(value)}`);
}
export function describePayment(p: Payment): string {
switch (p.status) {
case "pending":
return "Check your phone and enter your M-Pesa PIN to complete payment.";
case "succeeded":
return `Paid KES ${p.amountKes.toLocaleString("en-KE")}. M-Pesa receipt ${p.receipt}.`;
case "failed":
return `Payment failed: ${p.reason}`;
default:
return assertNever(p);
}
}
If someone later adds { status: "reversed"; ... } to the union, every switch that does not handle it becomes a compile error. That is exactly the behaviour you want for financial states.
Branded types for values that look alike
A Kenyan phone number, an order ID and an M-Pesa receipt are all strings, but mixing them up is a bug. Branded types make them distinct at compile time at zero runtime cost:
type Brand<T, Name extends string> = T & { readonly __brand: Name };
export type Msisdn = Brand<string, "Msisdn">;
export type OrderId = Brand<string, "OrderId">;
export function toMsisdn(raw: string): Msisdn {
const digits = raw.replace(/\D/g, "");
const normalised = digits.startsWith("0") ? `254${digits.slice(1)}` : digits;
if (!/^254(7|1)\d{8}$/.test(normalised)) {
throw new RangeError("Expected a Kenyan mobile number such as 0712345678 or 254712345678");
}
return normalised as Msisdn;
}
The only way to obtain an Msisdn is through the validating constructor, so any function that accepts Msisdn can trust its input. For money, store integer amounts (whole shillings for M-Pesa, or cents where your ledger requires them) rather than floating-point values.
Validate at the boundaries
TypeScript types are erased at compile time. await res.json() returns any, and req.body is whatever the client sent. Casting it with as Payment tells the compiler to trust data that nobody has checked.
The fix is to validate at every point where data enters your system:
+------------------- trusted zone --------------------+
HTTP request -->| [validate] -> typed domain logic -> [validate] --> |--> response
Webhook -->| [validate] -> |
Env vars -->| [validate at startup] |
3rd-party API-->| [validate response] |
+-----------------------------------------------------+
Inside the trusted zone, types are reliable. At the edge, a schema library performs runtime checks and produces typed values. Zod is a widely used choice; Valibot and ArkType are alternatives with similar ideas.
An end-to-end typed API: M-Pesa STK push
The example below uses a small monorepo layout. The same pattern works with any framework.
apps/
api/ Node.js + Express server
web/ Browser client (Angular, React, Vue or plain TS)
packages/
shared/ Zod schemas and inferred types used by both
1. Shared schemas
// packages/shared/src/schemas.ts
import { z } from "zod";
export const KenyanMsisdn = z
.string()
.regex(/^254(7|1)\d{8}$/, "Use the format 2547XXXXXXXX or 2541XXXXXXXX");
export const CreatePaymentRequest = z.object({
orderId: z.string().min(1).max(64),
phone: KenyanMsisdn,
amountKes: z.number().int().positive(), // M-Pesa amounts are whole shillings
});
export type CreatePaymentRequest = z.infer<typeof CreatePaymentRequest>;
export const PaymentStatus = z.discriminatedUnion("status", [
z.object({ status: z.literal("pending"), checkoutRequestId: z.string() }),
z.object({
status: z.literal("succeeded"),
receipt: z.string(),
amountKes: z.number().int(),
paidAt: z.string(),
}),
z.object({ status: z.literal("failed"), reason: z.string() }),
]);
export type PaymentStatus = z.infer<typeof PaymentStatus>;
// Shape of the Daraja STK push result callback
const CallbackItem = z.object({
Name: z.string(),
Value: z.union([z.string(), z.number()]).optional(),
});
export const StkCallback = z.object({
Body: z.object({
stkCallback: z.object({
MerchantRequestID: z.string(),
CheckoutRequestID: z.string(),
ResultCode: z.number(),
ResultDesc: z.string(),
CallbackMetadata: z.object({ Item: z.array(CallbackItem) }).optional(),
}),
}),
});
export type StkCallback = z.infer<typeof StkCallback>;
Each schema is both a runtime validator and, through z.infer, a static type. There is one source of truth.
2. Validated configuration
Misconfigured environment variables are a classic cause of production incidents. Validate them once at startup and fail fast:
// apps/api/src/env.ts
import { z } from "zod";
const Env = z.object({
PORT: z.coerce.number().int().default(3000),
DARAJA_BASE_URL: z.string().url(), // sandbox or production base URL from the Daraja portal
MPESA_SHORTCODE: z.string().regex(/^\d+$/),
MPESA_PASSKEY: z.string().min(1),
MPESA_CALLBACK_URL: z.string().url(),
});
export const env = Env.parse(process.env);
3. The API server
// apps/api/src/server.ts
import express from "express";
import { z } from "zod";
import {
CreatePaymentRequest,
PaymentStatus,
StkCallback,
} from "@app/shared";
import { env } from "./env.js";
import { getAccessToken } from "./daraja-auth.js"; // fetches and caches the OAuth token
const app = express();
app.use(express.json({ limit: "100kb" }));
// Demo storage only. Use a database with a unique index on CheckoutRequestID in production.
const payments = new Map<string, PaymentStatus>();
const StkPushResponse = z.object({
MerchantRequestID: z.string(),
CheckoutRequestID: z.string(),
ResponseCode: z.string(),
ResponseDescription: z.string(),
});
function darajaTimestamp(now: Date): string {
// Daraja expects YYYYMMDDHHmmss in East Africa Time (UTC+3, no daylight saving)
const eat = new Date(now.getTime() + 3 * 60 * 60 * 1000);
return eat.toISOString().replace(/[-:TZ]/g, "").slice(0, 14);
}
async function initiateStkPush(req: CreatePaymentRequest): Promise<string> {
const timestamp = darajaTimestamp(new Date());
const password = Buffer.from(
`${env.MPESA_SHORTCODE}${env.MPESA_PASSKEY}${timestamp}`,
).toString("base64");
const res = await fetch(`${env.DARAJA_BASE_URL}/mpesa/stkpush/v1/processrequest`, {
method: "POST",
headers: {
Authorization: `Bearer ${await getAccessToken()}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
BusinessShortCode: env.MPESA_SHORTCODE,
Password: password,
Timestamp: timestamp,
TransactionType: "CustomerPayBillOnline",
Amount: req.amountKes,
PartyA: req.phone,
PartyB: env.MPESA_SHORTCODE,
PhoneNumber: req.phone,
CallBackURL: env.MPESA_CALLBACK_URL,
AccountReference: req.orderId,
TransactionDesc: "Order payment",
}),
});
if (!res.ok) {
throw new Error(`STK push request failed with HTTP ${res.status}`);
}
const body = StkPushResponse.parse(await res.json());
if (body.ResponseCode !== "0") {
throw new Error(`STK push rejected: ${body.ResponseDescription}`);
}
return body.CheckoutRequestID;
}
function toPaymentStatus(cb: StkCallback["Body"]["stkCallback"]): PaymentStatus {
if (cb.ResultCode !== 0) {
return { status: "failed", reason: cb.ResultDesc };
}
const items = new Map(cb.CallbackMetadata?.Item.map((i) => [i.Name, i.Value]) ?? []);
const receipt = items.get("MpesaReceiptNumber");
const amount = items.get("Amount");
if (typeof receipt !== "string" || typeof amount !== "number") {
return { status: "failed", reason: "Success callback missing receipt or amount" };
}
return { status: "succeeded", receipt, amountKes: amount, paidAt: new Date().toISOString() };
}
app.post("/api/payments", async (req, res) => {
const parsed = CreatePaymentRequest.safeParse(req.body);
if (!parsed.success) {
res.status(400).json({ error: "invalid_request", issues: parsed.error.issues });
return;
}
try {
const checkoutRequestId = await initiateStkPush(parsed.data);
const status: PaymentStatus = { status: "pending", checkoutRequestId };
payments.set(checkoutRequestId, status);
res.status(202).json(status);
} catch (err: unknown) {
console.error(err instanceof Error ? err.message : err);
res.status(502).json({ error: "payment_provider_unavailable" });
}
});
app.get("/api/payments/:checkoutRequestId", (req, res) => {
const status = payments.get(req.params.checkoutRequestId);
if (!status) {
res.status(404).json({ error: "not_found" });
return;
}
res.json(status);
});
app.post("/api/mpesa/callback", (req, res) => {
const parsed = StkCallback.safeParse(req.body);
if (!parsed.success) {
res.status(400).end();
return;
}
const cb = parsed.data.Body.stkCallback;
payments.set(cb.CheckoutRequestID, toPaymentStatus(cb));
res.json({ ResultCode: 0, ResultDesc: "Accepted" });
});
app.listen(env.PORT, () => console.log(`API listening on port ${env.PORT}`));
Note how the callback handler validates the payload shape before reading any field, and looks up metadata items by name and checks their types rather than reading them by array position, because the order and presence of items should not be assumed. Production code should also protect the callback endpoint (for example with a hard-to-guess path segment and network allow-listing), make processing idempotent, and confirm the final status with Daraja's STK query API before releasing goods. Consult the official documentation at developer.safaricom.co.ke for current endpoints and payload details.
4. The typed client
The browser client imports the same schemas, so a change to the contract shows up as a compile error on both sides.
// apps/web/src/api.ts
import type { z } from "zod";
import { CreatePaymentRequest, PaymentStatus } from "@app/shared";
export class ApiError extends Error {
constructor(
public readonly status: number,
message: string,
) {
super(message);
}
}
async function request<T>(path: string, schema: z.ZodType<T>, init?: RequestInit): Promise<T> {
const res = await fetch(path, {
...init,
headers: { "Content-Type": "application/json" },
});
if (!res.ok) {
throw new ApiError(res.status, `Request to ${path} failed`);
}
return schema.parse(await res.json());
}
export function createPayment(input: CreatePaymentRequest): Promise<PaymentStatus> {
const body = CreatePaymentRequest.parse(input); // catch mistakes before the network call
return request("/api/payments", PaymentStatus, {
method: "POST",
body: JSON.stringify(body),
});
}
export function getPayment(checkoutRequestId: string): Promise<PaymentStatus> {
return request(`/api/payments/${encodeURIComponent(checkoutRequestId)}`, PaymentStatus);
}
A UI can now poll getPayment() every few seconds after the STK push and render the result with describePayment() from earlier, with the compiler guaranteeing that every status is handled. Validating responses on the client may seem redundant when you own the server, but it catches deployment mismatches, proxies returning HTML error pages, and partial rollouts where client and server versions differ.
The @app/shared import assumes a workspace package (npm, pnpm or Yarn workspaces). Alternatives with the same goal include tRPC, which shares types through function signatures, and OpenAPI-first workflows that generate TypeScript clients from a specification. The choice matters less than having a single source of truth.
A typical engineering setup: editor, terminal and the running app side by side.
Tooling that keeps standards high
- typescript-eslint with its type-aware rules, which catch floating promises, unsafe
anyusage and unnecessary conditions. - Prettier or an equivalent formatter, so code reviews focus on logic.
tsc --noEmitin CI, because many bundlers strip types without checking them.- Vitest or Jest for unit tests; type-level behaviour can be tested with
expectTypeOfin Vitest. - Dependency hygiene: keep TypeScript and
@types/*packages current. The TypeScript team has been working on a native compiler port for much faster builds; follow announcements on typescriptlang.org before adopting new major versions.
Common mistakes
- Using
asto silence errors. Every cast is an unchecked assumption. Prefer narrowing or validation. - Trusting
res.json(). External data isunknownuntil validated. - Optional fields instead of unions.
{ receipt?: string; error?: string }allows nonsense combinations. Use a discriminated union. - Floating-point money. Use integers for amounts, and agree on the unit (shillings or cents) across services.
- Defining types twice. Hand-written interfaces on the client and separate validators on the server drift apart. Derive both from one schema.
- Skipping strictness "for now". Retrofitting strict mode later costs far more than starting with it.
FAQ
Is TypeScript worth it for small projects?
Yes, for anything beyond a throwaway script. The setup cost is small with modern tooling, and the benefits in refactoring and editor support appear immediately.
Do I still need runtime validation if I use TypeScript?
Yes. TypeScript checks your code at compile time; it cannot check data arriving from users, partner APIs, webhooks or environment variables. Validate at every boundary.
Zod, tRPC or OpenAPI: which should I use?
Zod validates data at runtime. tRPC shares types between a TypeScript client and server. OpenAPI suits public or multi-language APIs. Many teams combine zod with either of the others.
Can I use these patterns in Angular, React and Vue?
Yes. The shared schemas and typed client are framework-agnostic. Each framework adds its own conventions for components and state, but the domain and boundary layers stay the same.
How TechBytes can help
We build TypeScript applications and payment integrations, including M-Pesa Daraja, card and bank APIs, with typed contracts and validation from the database to the browser. Our software development team can review an existing codebase, introduce strict mode incrementally or build new services alongside your engineers. For framework-specific guidance, see our Angular development practices for 2026.
