The TypeScript Architect designs type systems that eliminate entire categories of runtime errors before code ships. It covers strict configuration, generic design, discriminated unions, branded types, type-safe error handling, and the patterns that keep large TypeScript codebases maintainable as they grow. Every pattern here targets TypeScript 5.x with strict: true enabled.
Strict Configuration
// tsconfig.json - recommended base for new projects
{
"compilerOptions": {
"strict": true, // Enables all strict* flags
"noUncheckedIndexedAccess": true, // array[i] is T | undefined, not T
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"exactOptionalPropertyTypes": true, // { x?: string } ≠ { x: string | undefined }
"forceConsistentCasingInFileNames": true,
"moduleResolution": "bundler",
"target": "ES2022",
"lib": ["ES2022", "DOM"]
}
}
Discriminated Unions for Exhaustive State
// Model every mutually exclusive state as a union - never boolean flags
type RequestState<T> =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; error: string };
// The exhaustive switch forces handling of every state at compile time
function render<T>(state: RequestState<T>): string {
switch (state.status) {
case 'idle': return 'Not started';
case 'loading': return 'Loading...';
case 'success': return JSON.stringify(state.data);
case 'error': return 'Error: ' + state.error;
default:
// If a new state is added and this switch isn't updated,
// TypeScript errors here - the never type ensures exhaustiveness
const _exhaustive: never = state;
return _exhaustive;
}
}
Branded Types
// Prevent accidental mixing of IDs, currency amounts, etc.
type Brand<T, B extends string> = T & { readonly _brand: B };
type UserId = Brand<string, 'UserId'>;
type OrderId = Brand<string, 'OrderId'>;
type USDCents = Brand<number, 'USDCents'>;
const toUserId = (s: string): UserId => s as UserId;
const toOrderId = (s: string): OrderId => s as OrderId;
function getUser(id: UserId): Promise<User> { /* ... */ return Promise.resolve({} as User); }
// getUser(orderId); // ✅ TypeScript error - wrong brand
// getUser(rawString); // ✅ TypeScript error - unbranded string
Result Type for Safe Error Handling
type Ok<T> = { ok: true; value: T };
type Err<E> = { ok: false; error: E };
type Result<T, E = Error> = Ok<T> | Err<E>;
const ok = <T>(value: T): Ok<T> => ({ ok: true, value });
const err = <E>(error: E): Err<E> => ({ ok: false, error });
// Usage - no uncaught exceptions at the boundary
async function parseUser(raw: unknown): Promise<Result<User, string>> {
const parsed = userSchema.safeParse(raw);
if (!parsed.success) return err(parsed.error.message);
return ok(parsed.data);
}
const result = await parseUser(input);
if (!result.ok) {
console.error(result.error); // string - TypeScript knows
return;
}
console.log(result.value); // User - TypeScript knows
Utility Types Reference
| Utility | What it does | When to use |
|---|---|---|
Partial<T> | All properties optional | Patch/update payloads |
Required<T> | All properties required | After validation/defaults are applied |
Readonly<T> | All properties readonly | Immutable config objects |
Pick<T, K> | Keep only named keys | API response subsets |
Omit<T, K> | Remove named keys | Public versions of internal types |
ReturnType<F> | Infer function return type | Avoid duplicating types from functions |
Parameters<F> | Infer function param tuple | Higher-order function wrappers |
Awaited<T> | Unwrap a Promise type | Async return types |
Type-Safe API Boundaries
import { z } from 'zod';
// Define schema once - derive TypeScript type from it
const UserSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
role: z.enum(['admin', 'user', 'viewer']),
});
type User = z.infer<typeof UserSchema>;
// Validate at the API boundary - everything inside is typed
app.post('/users', async (req, res) => {
const result = UserSchema.safeParse(req.body);
if (!result.success) {
return res.status(400).json({ error: result.error.flatten() });
}
const user: User = result.data; // Fully typed, no assertions needed
await db.users.create(user);
res.json(user);
});