TypeScript Code Quality Patterns
Purpose
Guide for writing and reviewing TypeScript code with proper type safety, clean code principles, functional programming patterns, error handling, and project-specific conventions for the Saleor Configurator codebase.
When to Use
Configurator-Specific Tasks (Primary Triggers):
- Adding new entity types (category, product, channel, tax, etc.)
- Creating services (
*Service classes)
- Adding repository methods (
*Repository classes)
- Creating comparators for diff engine (
*Comparator classes)
- Adding formatters for output (
*Formatter classes)
- Implementing deployment stages
- Writing GraphQL queries/mutations
- Creating Zod schemas for validation
- Adding error classes (
*Error extends BaseError)
- Implementing bootstrap methods (idempotent create/update)
- Adding diff support for entities
General Writing Tasks:
- Implementing new features or services
- Adding new functions or methods
- Creating TypeScript classes or modules
- Writing transformation logic
- Refactoring existing code to clean patterns
Review Tasks:
- Reviewing code before committing
- Analyzing pull request changes
- Checking implementation quality
- Auditing existing code for improvements
Table of Contents
Quality Checklist
Use this checklist when writing new code to ensure quality from the start, or when reviewing existing code to identify improvements.
1. Type Safety Analysis
Critical (Must Fix):
Best Practices:
// BAD - Avoid these patterns
const result: any = someOperation();
const value = maybeUndefined!;
const data = response as unknown as MyType;
// GOOD - Use these patterns
type EntitySlug = string & { readonly __brand: unique symbol };
const isSlugBasedEntity = (entity: unknown): entity is { slug: string } => { ... };
const ENTITY_TYPES = ['categories', 'products'] as const;
// GOOD - satisfies for type validation while preserving literal types
interface ConfigShape {
readonly MAX_ITEMS: number;
readonly TIMEOUT: number;
}
const CONFIG = {
MAX_ITEMS: 10,
TIMEOUT: 5000,
} as const satisfies ConfigShape;
// CONFIG.MAX_ITEMS is `10`, not just `number`
// GOOD - Template literal type validation with satisfies
type CliFlag = `--${string}`;
const FLAGS = ["--json", "--verbose"] as const satisfies readonly CliFlag[];
2. Clean Code Principles
Function Quality:
Naming Conventions:
DRY (Don't Repeat Yourself):
Registry Pattern for Conditionals:
// BAD naming
const data = process(items);
const flag = check(user);
// GOOD naming
const categoriesToProcess = await fetchPendingCategories();
const isEntitySlugUnique = await validateSlugUniqueness(slug);
// BAD - Magic numbers
if (items.length > 10) { truncate(); }
const preview = text.slice(0, 30);
// GOOD - Named constants
const LIMITS = { MAX_ITEMS: 10, MAX_PREVIEW: 30 } as const;
if (items.length > LIMITS.MAX_ITEMS) { truncate(); }
const preview = text.slice(0, LIMITS.MAX_PREVIEW);
// BAD - Long if-else chain
function classify(error: Error): AppError {
if (error.message.includes("network")) return new NetworkError();
if (error.message.includes("auth")) return new AuthError();
if (error.message.includes("validation")) return new ValidationError();
return new UnexpectedError();
}
// GOOD - Registry pattern
interface ErrorMatcher {
matches: (msg: string) => boolean;
create: (error: Error) => AppError;
}
const ERROR_MATCHERS: ErrorMatcher[] = [
{ matches: (m) => m.includes("network"), create: () => new NetworkError() },
{ matches: (m) => m.includes("auth"), create: () => new AuthError() },
];
function classify(error: Error): AppError {
const matcher = ERROR_MATCHERS.find((m) => m.matches(error.message));
return matcher?.create(error) ?? new UnexpectedError();
}
3. Functional Programming Patterns
Immutability:
Composition:
Imperative to Functional Refactoring:
// BAD - Mutation
items.push(newItem);
entity.status = 'active';
// GOOD - Immutable
const updatedItems = [...items, newItem];
const updatedEntity = { ...entity, status: 'active' };
// BAD - Imperative loop with push
const lines: string[] = [];
for (const item of items) {
lines.push(formatItem(item));
}
// GOOD - Functional map
const lines = items.map(formatItem);
// BAD - forEach with conditional push
const results: Result[] = [];
items.forEach((item) => {
const match = item.match(regex);
if (match) {
results.push({ id: match[1] });
}
});
// GOOD - map + filter with type guard
const results = items
.map((item) => {
const match = item.match(regex);
return match ? { id: match[1] } : null;
})
.filter((r): r is Result => r !== null);
// BAD - Nested forEach
items.forEach((item) => {
lines.push(`Name: ${item.name}`);
item.details.forEach((d) => lines.push(` - ${d}`));
});
// GOOD - flatMap for nested structures
const lines = items.flatMap((item) => [
`Name: ${item.name}`,
...item.details.map((d) => ` - ${d}`),
]);
4. Zod Schema Usage
Schema Patterns:
Validation:
// GOOD pattern
const CategorySchema = BaseEntitySchema.extend({
slug: EntitySlugSchema,
parent: EntitySlugSchema.optional(),
});
type CategoryInput = z.infer<typeof CategorySchema>;
5. Error Handling
Error Types:
Error Design:
// GOOD error pattern
class EntityValidationError extends BaseError {
constructor(message: string, public readonly validationIssues: ValidationIssue[] = []) {
super(message, 'ENTITY_VALIDATION_ERROR');
}
getSuggestions(): string[] {
return ['Check entity configuration against schema'];
}
}
6. Performance Considerations
Avoid Anti-patterns:
Optimize:
// BAD - Creates new object each iteration
const result = items.reduce((acc, item) => ({ ...acc, [item.id]: item }), {});
// GOOD - Mutates Map directly
const result = items.reduce((acc, item) => acc.set(item.id, item), new Map());
Review Output Format
Structure findings as:
Critical Issues
Items that must be fixed before merge.
Important Improvements
Items that should be addressed but aren't blocking.
Suggestions
Nice-to-have improvements for future consideration.
Positive Observations
Well-implemented patterns worth highlighting.
Project-Specific Conventions
- Entity identification: Slug-based (categories, products) vs Name-based (productTypes, pageTypes)
- Service pattern: Constructor DI with validator, repository, logger
- Repository pattern: GraphQL operations encapsulated
- Test pattern: vi.fn() mocks with schema-generated test data
References
Skill Reference Files
- Anti-Patterns - Common anti-patterns with corrections
- Type Safety Examples - Type guards, branded types, discriminated unions
Project Resources
- See
{baseDir}/docs/CODE_QUALITY.md for complete coding standards
- See
{baseDir}/docs/ARCHITECTURE.md for service patterns
- See
{baseDir}/biome.json for linting rules
Related Skills
- Complete entity workflow: See
adding-entity-types for architectural patterns
- Zod standards: See
designing-zod-schemas for schema review criteria
- Pre-commit checks: See
validating-pre-commit for quality gate commands
1---2name: reviewing-typescript-code-23description: "TypeScript code quality patterns for writing and reviewing code. Covers type safety, clean code, functional patterns, Zod usage, and error handling. Triggers on: add entity, create service, add repository, create comparator, add formatter, deployment stage, GraphQL query, GraphQL mutation, bootstrap method, diff support, command handler, Zod schema, error class, implement feature, add function, refactor code, clean code, functional patterns, map filter reduce, satisfies operator, type guard, code review, PR review, check implementation, audit code, fix types."4allowed-tools: "Read, Grep, Glob"5metadata:6 source: https://skillmd.com/skills/majiayu000/reviewing-typescript-code-27---89# TypeScript Code Quality Patterns1011## Purpose1213Guide for writing and reviewing TypeScript code with proper type safety, clean code principles, functional programming patterns, error handling, and project-specific conventions for the Saleor Configurator codebase.1415## When to Use1617**Configurator-Specific Tasks (Primary Triggers):**18- Adding new entity types (category, product, channel, tax, etc.)19- Creating services (`*Service` classes)20- Adding repository methods (`*Repository` classes)21- Creating comparators for diff engine (`*Comparator` classes)22- Adding formatters for output (`*Formatter` classes)23- Implementing deployment stages24- Writing GraphQL queries/mutations25- Creating Zod schemas for validation26- Adding error classes (`*Error` extends `BaseError`)27- Implementing bootstrap methods (idempotent create/update)28- Adding diff support for entities2930**General Writing Tasks:**31- Implementing new features or services32- Adding new functions or methods33- Creating TypeScript classes or modules34- Writing transformation logic35- Refactoring existing code to clean patterns3637**Review Tasks:**38- Reviewing code before committing39- Analyzing pull request changes40- Checking implementation quality41- Auditing existing code for improvements4243## Table of Contents4445- [Quality Checklist](#quality-checklist)46 - [Type Safety Analysis](#1-type-safety-analysis)47 - [Clean Code Principles](#2-clean-code-principles)48 - [Functional Programming Patterns](#3-functional-programming-patterns)49 - [Zod Schema Usage](#4-zod-schema-usage)50 - [Error Handling](#5-error-handling)51 - [Performance Considerations](#6-performance-considerations)52- [Review Output Format](#review-output-format)53- [Project-Specific Conventions](#project-specific-conventions)54- [References](#references)5556## Quality Checklist5758Use this checklist when **writing new code** to ensure quality from the start, or when **reviewing existing code** to identify improvements.5960### 1. Type Safety Analysis6162**Critical (Must Fix)**:63- [ ] No `any` types in production code (only allowed in test mocks)64- [ ] No unsafe type assertions (`as unknown as T`)65- [ ] No non-null assertions (`!`) without strong justification66- [ ] Proper type guards for runtime validation6768**Best Practices**:69- [ ] Branded types used for domain-specific values (EntitySlug, EntityName)70- [ ] Discriminated unions preferred over inheritance71- [ ] Type inference leveraged where clear72- [ ] Generic constraints properly applied73- [ ] `readonly` used for immutable data74- [ ] `satisfies` operator for type validation with literal preservation7576```typescript77// BAD - Avoid these patterns78const result: any = someOperation();79const value = maybeUndefined!;80const data = response as unknown as MyType;8182// GOOD - Use these patterns83type EntitySlug = string & { readonly __brand: unique symbol };84const isSlugBasedEntity = (entity: unknown): entity is { slug: string } => { ... };85const ENTITY_TYPES = ['categories', 'products'] as const;8687// GOOD - satisfies for type validation while preserving literal types88interface ConfigShape {89 readonly MAX_ITEMS: number;90 readonly TIMEOUT: number;91}92const CONFIG = {93 MAX_ITEMS: 10,94 TIMEOUT: 5000,95} as const satisfies ConfigShape;96// CONFIG.MAX_ITEMS is `10`, not just `number`9798// GOOD - Template literal type validation with satisfies99type CliFlag = `--${string}`;100const FLAGS = ["--json", "--verbose"] as const satisfies readonly CliFlag[];101```102103### 2. Clean Code Principles104105**Function Quality**:106- [ ] Single Responsibility Principle followed107- [ ] Functions are small (< 20 lines ideally)108- [ ] Pure functions where possible (no side effects)109- [ ] Meaningful, declarative names used110- [ ] Arrow functions for consistency111112**Naming Conventions**:113- [ ] Functions describe what they do, not how114- [ ] Variables are descriptive and context-specific115- [ ] Boolean names start with `is`, `has`, `should`, `can`116- [ ] Collections use plural names117118**DRY (Don't Repeat Yourself)**:119- [ ] Shared utilities extracted to dedicated modules120- [ ] Magic numbers replaced with named constants121- [ ] Repeated logic extracted to helper functions122- [ ] Constants grouped in config objects123124**Registry Pattern for Conditionals**:125- [ ] Long if-else chains refactored to registry/strategy pattern126- [ ] Error classification uses matcher registry127- [ ] Type dispatch uses discriminated unions or maps128129```typescript130// BAD naming131const data = process(items);132const flag = check(user);133134// GOOD naming135const categoriesToProcess = await fetchPendingCategories();136const isEntitySlugUnique = await validateSlugUniqueness(slug);137138// BAD - Magic numbers139if (items.length > 10) { truncate(); }140const preview = text.slice(0, 30);141142// GOOD - Named constants143const LIMITS = { MAX_ITEMS: 10, MAX_PREVIEW: 30 } as const;144if (items.length > LIMITS.MAX_ITEMS) { truncate(); }145const preview = text.slice(0, LIMITS.MAX_PREVIEW);146147// BAD - Long if-else chain148function classify(error: Error): AppError {149 if (error.message.includes("network")) return new NetworkError();150 if (error.message.includes("auth")) return new AuthError();151 if (error.message.includes("validation")) return new ValidationError();152 return new UnexpectedError();153}154155// GOOD - Registry pattern156interface ErrorMatcher {157 matches: (msg: string) => boolean;158 create: (error: Error) => AppError;159}160const ERROR_MATCHERS: ErrorMatcher[] = [161 { matches: (m) => m.includes("network"), create: () => new NetworkError() },162 { matches: (m) => m.includes("auth"), create: () => new AuthError() },163];164function classify(error: Error): AppError {165 const matcher = ERROR_MATCHERS.find((m) => m.matches(error.message));166 return matcher?.create(error) ?? new UnexpectedError();167}168```169170### 3. Functional Programming Patterns171172**Immutability**:173- [ ] No direct mutation of arrays or objects174- [ ] Spread operator or immutable methods used175- [ ] `Map` preferred over object for frequent lookups176177**Composition**:178- [ ] Small, composable functions179- [ ] Higher-order functions for reusable logic180- [ ] Pipeline patterns where appropriate181182**Imperative to Functional Refactoring**:183- [ ] `for` loops replaced with `map`/`filter`/`reduce`184- [ ] `forEach` with push replaced with spread + `map`185- [ ] Nested loops replaced with `flatMap`186- [ ] Conditional accumulation uses `map` + `filter` with type guards187188```typescript189// BAD - Mutation190items.push(newItem);191entity.status = 'active';192193// GOOD - Immutable194const updatedItems = [...items, newItem];195const updatedEntity = { ...entity, status: 'active' };196197// BAD - Imperative loop with push198const lines: string[] = [];199for (const item of items) {200 lines.push(formatItem(item));201}202203// GOOD - Functional map204const lines = items.map(formatItem);205206// BAD - forEach with conditional push207const results: Result[] = [];208items.forEach((item) => {209 const match = item.match(regex);210 if (match) {211 results.push({ id: match[1] });212 }213});214215// GOOD - map + filter with type guard216const results = items217 .map((item) => {218 const match = item.match(regex);219 return match ? { id: match[1] } : null;220 })221 .filter((r): r is Result => r !== null);222223// BAD - Nested forEach224items.forEach((item) => {225 lines.push(`Name: ${item.name}`);226 item.details.forEach((d) => lines.push(` - ${d}`));227});228229// GOOD - flatMap for nested structures230const lines = items.flatMap((item) => [231 `Name: ${item.name}`,232 ...item.details.map((d) => ` - ${d}`),233]);234```235236### 4. Zod Schema Usage237238**Schema Patterns**:239- [ ] Schemas defined before implementing logic240- [ ] Type inference with `z.infer<>`241- [ ] Reusable schema primitives (EntitySlugSchema, EntityNameSchema)242- [ ] Discriminated unions for variant types243- [ ] Transform and refinement used appropriately244245**Validation**:246- [ ] `safeParse` for error handling247- [ ] Detailed error messages with context248- [ ] Schema reuse in tests249250```typescript251// GOOD pattern252const CategorySchema = BaseEntitySchema.extend({253 slug: EntitySlugSchema,254 parent: EntitySlugSchema.optional(),255});256257type CategoryInput = z.infer<typeof CategorySchema>;258```259260### 5. Error Handling261262**Error Types**:263- [ ] Specific error types extend `BaseError`264- [ ] GraphQL errors wrapped with `GraphQLError.fromCombinedError()`265- [ ] Zod errors wrapped with `ZodValidationError.fromZodError()`266- [ ] Error messages are actionable267268**Error Design**:269- [ ] Error includes relevant context270- [ ] Recovery suggestions provided271- [ ] Error codes for machine processing272273```typescript274// GOOD error pattern275class EntityValidationError extends BaseError {276 constructor(message: string, public readonly validationIssues: ValidationIssue[] = []) {277 super(message, 'ENTITY_VALIDATION_ERROR');278 }279280 getSuggestions(): string[] {281 return ['Check entity configuration against schema'];282 }283}284```285286### 6. Performance Considerations287288**Avoid Anti-patterns**:289- [ ] No accumulating spreads in reduce290- [ ] No function creation in loops291- [ ] No unnecessary object creation292293**Optimize**:294- [ ] Use `Map` for frequent lookups295- [ ] Lazy evaluation for expensive operations296- [ ] Memoization where appropriate297298```typescript299// BAD - Creates new object each iteration300const result = items.reduce((acc, item) => ({ ...acc, [item.id]: item }), {});301302// GOOD - Mutates Map directly303const result = items.reduce((acc, item) => acc.set(item.id, item), new Map());304```305306## Review Output Format307308Structure findings as:309310### Critical Issues311Items that must be fixed before merge.312313### Important Improvements314Items that should be addressed but aren't blocking.315316### Suggestions317Nice-to-have improvements for future consideration.318319### Positive Observations320Well-implemented patterns worth highlighting.321322## Project-Specific Conventions323324- Entity identification: Slug-based (categories, products) vs Name-based (productTypes, pageTypes)325- Service pattern: Constructor DI with validator, repository, logger326- Repository pattern: GraphQL operations encapsulated327- Test pattern: vi.fn() mocks with schema-generated test data328329## References330331### Skill Reference Files332- **[Anti-Patterns](references/anti-patterns.md)** - Common anti-patterns with corrections333- **[Type Safety Examples](references/type-safety-examples.md)** - Type guards, branded types, discriminated unions334335### Project Resources336- See `{baseDir}/docs/CODE_QUALITY.md` for complete coding standards337- See `{baseDir}/docs/ARCHITECTURE.md` for service patterns338- See `{baseDir}/biome.json` for linting rules339340## Related Skills341342- **Complete entity workflow**: See `adding-entity-types` for architectural patterns343- **Zod standards**: See `designing-zod-schemas` for schema review criteria344- **Pre-commit checks**: See `validating-pre-commit` for quality gate commands