Safety-Critical Coding Rules for TypeScript
Adapted from NASA's JPLThe Power of 10 rules originated from NASA's Jet Propulsion Laboratory as guidelines for writing safety-critical code. This project adapts those proven principles for modern TypeScript development, helping you write more reliable, maintainable, and bug-free code.
Avoid recursion, nested callbacks (3+ levels), and callback hell. Use for/while loops, Array methods, and async/await for cleaner, more predictable code flow.
// ❌ Avoid - nested callbacks
getData(function(err, data) {
processData(data, function(err2, result) {
saveResult(result, function(err3) { });
});
});
// ✅ Preferred - async/await
const data = await getData();
const result = await processData(data);
await saveResult(result);
Avoid while(true) with unclear termination. Use explicit bounds and max iterations to prevent infinite loops and make code behavior predictable.
// ❌ Avoid - unclear termination
while (true) {
const item = queue.pop();
if (!item) break;
process(item);
}
// ✅ Preferred - explicit bounds
const MAX_ITEMS = 1000;
for (let i = 0; i < Math.min(queue.length, MAX_ITEMS); i++) {
process(queue[i]);
}
Avoid creating new objects in loops and closures that capture large scope. Pre-allocate and reuse objects to reduce GC pressure and improve performance.
// ❌ Avoid - creating objects in loop
function processItems(items: string[]) {
return items.map(item => new ProcessedItem(item));
}
// ✅ Preferred - reuse primitives
function processItems(items: string[]): string[] {
return items.map(item => item.trim().toLowerCase());
}
Avoid functions over 40 lines with 3+ nesting levels. Prefer single responsibility and extract helper functions for better readability and testability.
// ❌ Avoid - large function with deep nesting
async function handleUserRequest(req: Request) {
if (req.method === 'GET') {
const user = await db.findUser(req.userId);
if (user) {
if (user.isActive) {
// ... 50 more lines
}
}
}
}
// ✅ Preferred - small, focused functions
async function handleUserRequest(req: Request): Promise<Response> {
if (!isGetRequest(req)) return badRequest();
const user = await fetchUser(req.userId);
if (!user) return notFound();
return ok(await serializeUser(user));
}
Avoid missing null checks and assuming valid input. Use assert libraries, Zod, or similar for runtime validation of external input.
// ❌ Avoid - assume valid input
function calculateShipping(order: Order): number {
return order.items.reduce((sum, item) => sum + item.price, 0);
}
// ✅ Preferred - validate with Zod
import { z } from 'zod';
const OrderSchema = z.object({
items: z.array(z.object({ price: z.number().positive() })).min(1)
});
function calculateShipping(order: unknown): number {
const validOrder = OrderSchema.parse(order);
return validOrder.items.reduce((sum, item) => sum + item.price, 0);
}
Avoid global variables and unused class properties. Use const by default and declare variables at their point of use to reduce coupling.
// ❌ Avoid - global state
let globalCounter = 0;
class Counter {
increment() { globalCounter++; }
}
// ✅ Preferred - local scope
function createCounter() {
let counter = 0;
return {
increment: () => counter++
};
}
Avoid the any type and ignoring strict mode. Enable strict: true in TypeScript and add runtime validation for external data.
// ❌ Avoid - any type
function parseData(data: any): any {
return JSON.parse(data);
}
// ✅ Preferred - strict typing
interface UserData {
id: string;
name: string;
email: string;
}
function parseData(data: string): UserData {
const parsed = JSON.parse(data) as UserData;
if (!parsed.id || !parsed.name || !parsed.email) {
throw new Error('Invalid user data');
}
return parsed;
}
Avoid dynamic requires and complex conditionals. Prefer static imports and simple environment configuration for better tooling support.
// ❌ Avoid - dynamic requires
function loadDriver(name: string) {
return require(\`./drivers/\${name}\`);
}
// ✅ Preferred - static imports
import { PostgresDriver } from './drivers/postgres';
import { MySQLDriver } from './drivers/mysql';
const drivers = { postgres: PostgresDriver, mysql: MySQLDriver };
function getDriver(type: 'postgres' | 'mysql'): Driver {
return new drivers[type]();
}
Avoid deep nesting (a.b.c.d) and chained optional chaining. Prefer flat structures and immutable updates for predictable state changes.
// ❌ Avoid - deep nesting
const user = getUser();
const city = user?.profile?.address?.city?.toString();
// ✅ Preferred - flat, explicit
interface Address { city: string; }
interface Profile { address: Address; }
interface User { profile: Profile; }
function getCity(user: User | null): string {
if (!user?.profile?.address) return 'Unknown';
return user.profile.address.city;
}
// Immutable updates
const updateUser = (user: User, name: string): User => ({
...user,
name,
profile: { ...user.profile }
});
Avoid disabling strict mode or using @ts-ignore. Enable strict: true in tsconfig and ESLint with zero warnings for maximum type safety.
// tsconfig.json
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"noUnusedLocals": true,
"noUnusedParameters": true
}
}
// .eslintrc.yml
rules:
no-unused-vars: error
no-implicit-any: error