TypeScript strict mode patterns. Use when writing any TypeScript code.
any - ever. Use unknown if type is truly unknownas Type) without justificationtype over interface for data structuresinterface for behavior contracts onlytype — for data structuresexport type User = {
readonly id: string;
readonly email: string;
readonly name: string;
readonly roles: ReadonlyArray<string>;
};
Why type? Better for unions, intersections, mapped types. readonly signals immutability. More flexible composition with utility types.
interface — for behavior contractsexport interface UserRepository {
findById(id: string): Promise<User | undefined>;
save(user: User): Promise<void>;
}
Why interface? Signals "this must be implemented." Works with implements keyword. Conventional for dependency injection.
Define schemas once, import everywhere. Never duplicate the same validation logic across multiple files.
// ✅ Define once
export const CreateUserRequestSchema = z.object({
email: z.string().email(),
name: z.string().min(1),
});
export type CreateUserRequest = z.infer<typeof CreateUserRequestSchema>;
// Import and use wherever needed
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noPropertyAccessFromIndexSignature": true,
"forceConsistentCasingInFileNames": true,
"allowUnusedLabels": false
}
}
Core strict flags:
strict: true - Enables all strict type checking optionsnoImplicitAny - Error on expressions/declarations with implied any typestrictNullChecks - null and undefined have their own types (not assignable to everything)noUnusedLocals - Error on unused local variablesnoUnusedParameters - Error on unused function parametersnoImplicitReturns - Error when not all code paths return a valuenoFallthroughCasesInSwitch - Error on fallthrough cases in switch statementsAdditional safety flags (CRITICAL):
noUncheckedIndexedAccess - Array/object access returns T | undefined (prevents runtime errors from assuming elements exist)exactOptionalPropertyTypes - Distinguishes property?: T from property: T | undefined (more precise types)noPropertyAccessFromIndexSignature - Requires bracket notation for index signature properties (forces awareness of dynamic access)forceConsistentCasingInFileNames - Prevents case sensitivity issues across operating systemsallowUnusedLabels - Error on unused labels (catches accidental labels that do nothing)@ts-ignore without explicit comments explaining whyThe noUnusedParameters rule can reveal architectural problems:
Example: A function with an unused parameter often indicates the parameter belongs in a different layer. Strict mode catches these design issues early.
For detailed patterns on immutability (readonly, ReadonlyArray), pure functions, composition, Result types, array methods, and factory functions, see the functional skill. These are the canonical patterns used across the codebase.
Key TypeScript-specific notes:
readonly on all type properties and ReadonlyArray<T> for arraysreadonly is used — leverage this// API responses, user input, external data
const UserSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
});
type User = z.infer<typeof UserSchema>;
// Validate at boundary
const user = UserSchema.parse(apiResponse);
Partial<T>, Pick<T>, etc.)// ✅ CORRECT - No schema needed
type Result<T, E> =
| { success: true; data: T }
| { success: false; error: E };
// ✅ CORRECT - Interface, no validation
interface UserService {
createUser(user: User): void;
}
For type-safe primitives:
type UserId = string & { readonly brand: unique symbol };
type PaymentAmount = number & { readonly brand: unique symbol };
// Type-safe at compile time
const processPayment = (userId: UserId, amount: PaymentAmount) => {
// Implementation
};
// ❌ Can't pass raw string/number
processPayment('user-123', 100); // Error
// ✅ Must use branded type
const userId = 'user-123' as UserId;
const amount = 100 as PaymentAmount;
processPayment(userId, amount); // OK
When writing TypeScript code, verify:
any types - using unknown where type is truly unknowntype for data structures with readonlyinterface for behavior contractsfunctional skill