⚡ AutoSnippets PRO PL

TypeScript: Production Code Snippets

TypeScript patterns: dependency injection, type validation, generic repositories.

Python JavaScript TypeScript Java C# C++ Go PHP Rust SQL

On this page:

11. TypeScript: DI Container (Generics)

TypeScript

A manual implementation of the inversion-of-control pattern using generics.

class Container {
    private services = new Map();

    register(name: string, instance: T): void {
        this.services.set(name, instance);
    }

    resolve(name: string): T {
        const service = this.services.get(name);
        if (!service) throw new Error(`Service not found: ${name}`);
        return service as T;
    }
}

When to use

Used in larger applications where dependencies between many services need managing without passing them around manually.

Common pitfalls

Registering a service under the wrong name (a typo in a string) only fails at runtime — consider typed keys instead of plain strings.

12. TypeScript: Environment Variable Parser

TypeScript

Validating environment configuration using the Zod library.

import { z } from 'zod';

const envSchema = z.object({
    PORT: z.string().transform(Number),
    DATABASE_URL: z.string().url(),
    NODE_ENV: z.enum(['development', 'production'])
});

export const env = envSchema.parse(process.env);

When to use

Worth using at every application's startup, to catch missing or invalid configuration immediately rather than at runtime.

Common pitfalls

Zod throws on the first validation error — if you want to see all errors at once, use the .safeParse() method instead of .parse().

13. TypeScript: Generic Repository Pattern

TypeScript

Database operation abstraction for arbitrary TypeScript models.

interface IRepository {
    findById(id: string): Promise;
    save(entity: T): Promise;
}

class InMemoryRepository implements IRepository {
    private items = new Map();
    async findById(id: string): Promise { return this.items.get(id) || null; }
    async save(entity: T): Promise { this.items.set(entity.id, entity); }
}

When to use

Useful when you have many similar data models and don't want to write the same CRUD code for each one separately.

Common pitfalls

An overly generic repository can be hard to extend with specific queries — sometimes it's better to add separate methods for concrete models.

14. TypeScript: Runtime Struct Validator

TypeScript

Deep type checking of nested objects via Type Guards.

interface User { id: string; name: string; }

function isUser(obj: any): obj is User {
    return obj 
        && typeof obj === 'object' 
        && typeof obj.id === 'string' 
        && typeof obj.name === 'string';
}

When to use

Useful for validating data coming from outside (API, JSON file), where TypeScript alone doesn't check types at runtime.

Common pitfalls

A type guard only checks the top-level structure — nested objects need additional checks or a library like Zod.

15. TypeScript: Strongly Typed Logger

TypeScript

A production event logging system with log-level interfaces.

type LogLevel = 'INFO' | 'WARN' | 'ERROR';

class TypedLogger {
    private log(level: LogLevel, message: string, meta?: Record) {
        console.log(JSON.stringify({ timestamp: new Date().toISOString(), level, message, ...meta }));
    }
    info(msg: string, meta?: Record) { this.log('INFO', msg, meta); }
    error(msg: string, meta?: Record) { this.log('ERROR', msg, meta); }
}

When to use

Makes analyzing production logs easier, since every entry has a consistent JSON structure that's easy to search in tools like Datadog or ELK.

Common pitfalls

Logging straight to the console is often insufficient in production — eventually wire it up to a proper transport (file, external service).