TypeScript Standards
Auto-loads for projects with TypeScript in their tech stack.
Metadata
| Field | Value |
|---|---|
| Type | context |
| Applies to | typescript, nodejs, express, nestjs, nextjs, react, vue, angular, deno, bun, zod |
Core Principles
- Simplicity - Simple, understandable code
- Readability - Readability over cleverness
- Maintainability - Code that’s easy to maintain
- Testability - Code that’s easy to test
- DRY - Don’t Repeat Yourself
Naming Conventions
| Element | Convention | Example |
|---|---|---|
| Variables/Functions | camelCase | getUserById, isActive |
| Classes/Interfaces/Types | PascalCase | UserService, ApiClient |
| Constants | UPPER_SNAKE_CASE | MAX_RETRY_COUNT |
| Files | kebab-case | user-service.ts |
| Interfaces | No I prefix | User not IUser |
Code Style
// Explicit types for function parameters and return values
function getUserById(userId: string): User | undefined {
if (!userId) {
throw new Error("userId cannot be empty");
}
// implementation...
}
// Prefer interfaces for object shapes
interface User {
id: string;
name: string;
email: string;
age?: number;
}
// Type aliases for unions and primitives
type UserId = string;
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";Best Practices
// Nullish coalescing and optional chaining
const name = user?.profile?.name ?? "Anonymous";
// Readonly for immutable data
interface Config {
readonly apiUrl: string;
readonly maxRetries: number;
}
// as const for literal types
const DIRECTIONS = ["north", "south", "east", "west"] as const;
type Direction = typeof DIRECTIONS[number];
// Prefer unknown over any
function parseJson(input: string): unknown {
return JSON.parse(input);
}Utility Types
type UserUpdate = Partial<User>; // All optional
type UserPreview = Pick<User, "id" | "name">; // Select properties
type UserWithoutEmail = Omit<User, "email">; // Exclude propertiesZod for Runtime Validation
import { z } from "zod";
const UserSchema = z.object({
id: z.string().uuid(),
name: z.string().min(1).max(100),
email: z.string().email(),
});
type User = z.infer<typeof UserSchema>;
const user = UserSchema.parse(untrustedData);Recommended Tooling
| Tool | Purpose |
|---|---|
pnpm or bun | Package manager |
eslint | Linting with TypeScript rules |
prettier | Code formatting |
vitest or jest | Testing framework |
zod | Runtime validation |
tsconfig.json
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitReturns": true,
"forceConsistentCasingInFileNames": true
}
}