Here’s the most readable TypeScript code example with best practices, comprehensive documentation, strong typing, and excellent structure

Key TypeScript-specific readability features:

✅ Strong Type Safety - Interfaces, enums, and strict typing everywhere ✅ JSDoc with @example - Code examples in documentation ✅ Readonly properties - Prevents accidental mutations ✅ Private/public modifiers - Clear access control ✅ Generic types - OperationResult for type-safe returns ✅ Nullish coalescing - ?? operator for safe defaults ✅ Type guards - typeof checks for runtime safety ✅ Enums - OperationStatus enum instead of strings ✅ Interface definitions - Clear contracts for objects ✅ Return type annotations - Every function has explicit return type ✅ Parameter types - All parameters fully typed ✅ Const assertions - as const for CONFIG ✅ Comprehensive comments - Every class and method documented ✅ Modern best practices - Optional chaining ??, nullish coalescing ✅ Logical grouping - Section dividers and organization ✅ Error handling - Type-safe error messages and results ✅ Immutability - ReadonlyArray return types

This provides maximum type safety while maintaining excellent readability!

/**
 * =============================================================================
 * PROJECT:  Data Management System
 * AUTHOR:   AndrewMaksimchuk
 * DATE:     2026-03-23
 * LANGUAGE: TypeScript
 * PURPOSE:  Demonstrate highly readable TypeScript code with type safety,
 *           comprehensive documentation, meaningful naming, and best practices.
 * =============================================================================
 */

'use strict';

/**
 * =============================================================================
 * ENUMS AND TYPES
 * =============================================================================
 */

/**
 * Represents the status of an operation
 */
enum OperationStatus {
        SUCCESS = 'success',
        FAILURE = 'failure',
        VALIDATION_ERROR = 'validation_error',
        NOT_FOUND = 'not_found',
}

/**
 * Represents the validation result of an operation
 */
interface ValidationResult {
        isValid: boolean;
        error?: string;
}

/**
 * Represents the result of an operation
 */
interface OperationResult<T = unknown> {
        status: OperationStatus;
        data?: T;
        error?: string;
}

/**
 * =============================================================================
 * CONSTANTS AND CONFIGURATION
 * =============================================================================
 */

/**
 * Application configuration constants
 */
const CONFIG = {
        MAX_NAME_LENGTH: 64,
        MAX_EMAIL_LENGTH: 128,
        MAX_PHONE_LENGTH: 20,
        MAX_DESCRIPTION_LENGTH: 256,
        MAX_RECORDS: 1000,
        MIN_AGE: 18,
        MAX_AGE: 150,
        EMAIL_REGEX: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
        PHONE_REGEX: /^[\d\s\-\(\)]+$/,
} as const;

/**
 * =============================================================================
 * DATA STRUCTURES / CLASSES
 * =============================================================================
 */

/**
 * PersonRecord class
 *
 * Represents a single person with contact information and metadata.
 * Encapsulates all data for a person record with full type safety.
 *
 * @example
 * const person = new PersonRecord({
 *   id: 1,
 *   name: 'Alice Johnson',
 *   email: 'alice@example.com',
 *   phone: '555-1234',
 *   age: 28,
 *   isActive: true
 * });
 */
class PersonRecord {
        /** Unique identifier for this record */
        readonly id: number | null;

        /** Person's full name */
        readonly name: string;

        /** Person's email address */
        readonly email: string;

        /** Person's phone number */
        readonly phone: string;

        /** Person's age in years */
        readonly age: number;

        /** Whether this record is currently active */
        readonly isActive: boolean;

        /** Timestamp when the record was created */
        readonly createdAt: Date;

        /** Timestamp when the record was last updated */
        readonly updatedAt: Date;

        /**
         * Creates a new PersonRecord instance
         *
         * @param data - The data object containing person information
         * @throws {Error} If required fields are missing or invalid
         *
         * @example
         * const person = new PersonRecord({
         *   id: 1,
         *   name: 'Alice',
         *   email: 'alice@example.com',
         *   phone: '555-1234',
         *   age: 28
         * });
         */
        constructor(data: Partial<PersonRecord> = {}) {
                this.id = data.id ?? null;
                this.name = data.name ?? '';
                this.email = data.email ?? '';
                this.phone = data.phone ?? '';
                this.age = data.age ?? 0;
                this.isActive = data.isActive ?? true;
                this.createdAt = data.createdAt ?? new Date();
                this.updatedAt = data.updatedAt ?? new Date();
        }

        /**
         * Returns a deep copy of this record
         *
         * @returns A new PersonRecord with copied data
         */
        clone(): PersonRecord {
                return new PersonRecord({
                        id: this.id,
                        name: this.name,
                        email: this.email,
                        phone: this.phone,
                        age: this.age,
                        isActive: this.isActive,
                        createdAt: new Date(this.createdAt),
                        updatedAt: new Date(this.updatedAt),
                });
        }

        /**
         * Converts record to plain JavaScript object
         *
         * @returns Plain object representation of the record
         */
        toJSON(): Record<string, unknown> {
                return {
                        id: this.id,
                        name: this.name,
                        email: this.email,
                        phone: this.phone,
                        age: this.age,
                        isActive: this.isActive,
                        createdAt: this.createdAt.toISOString(),
                        updatedAt: this.updatedAt.toISOString(),
                };
        }

        /**
         * Returns a formatted string representation of the record
         *
         * @returns Formatted display string
         */
        toString(): string {
                return `PersonRecord(id=${this.id}, name="${this.name}", email="${this.email}")`;
        }
}

/**
 * PersonDataStore class
 *
 * Central data storage container managing all person records.
 * Provides type-safe methods for CRUD operations, validation, and querying.
 *
 * @example
 * const store = new PersonDataStore();
 * const result = store.addRecord('Alice', 'alice@example.com', '555-1234', 28);
 * if (result.status === OperationStatus.SUCCESS) {
 *   console.log(`Added record with ID: ${result.data}`);
 * }
 */
class PersonDataStore {
        /** Stores all person records */
        private readonly records: PersonRecord[] = [];

        /** Next ID to assign to a new record */
        private nextId: number = 1;

        /** Maximum number of records to store */
        private readonly maxRecords: number;

        /** Flag indicating unsaved changes */
        private isModified: boolean = false;

        /** Most recent error message */
        private lastErrorMessage: string = '';

        /**
         * Creates a new PersonDataStore instance
         *
         * @param options - Configuration options
         * @param options.maxRecords - Maximum number of records to store (default: 1000)
         *
         * @example
         * const store = new PersonDataStore({ maxRecords: 500 });
         */
        constructor(options: { maxRecords?: number } = {}) {
                this.maxRecords = options.maxRecords ?? CONFIG.MAX_RECORDS;
        }

        /**
         * Clears all error state
         *
         * @private
         */
        private clearError(): void {
                this.lastErrorMessage = '';
        }

        /**
         * Sets an error message
         *
         * @private
         * @param message - The error message to set
         */
        private setError(message: string): void {
                this.lastErrorMessage = message;
                console.error(`[DataStore Error]: ${message}`);
        }

        /**
         * Gets the last error message
         *
         * @returns The last error message or empty string
         */
        getLastError(): string {
                return this.lastErrorMessage;
        }

        /**
         * Validates a person's name
         *
         * @private
         * @param name - The name to validate
         * @returns Validation result with error message if invalid
         */
        private validateName(name: unknown): ValidationResult {
                if (typeof name !== 'string') {
                        return { isValid: false, error: 'Name must be a string' };
                }

                if (name.trim().length === 0) {
                        return { isValid: false, error: 'Name cannot be empty' };
                }

                if (name.length > CONFIG.MAX_NAME_LENGTH) {
                        return {
                                isValid: false,
                                error: `Name exceeds maximum length of ${CONFIG.MAX_NAME_LENGTH}`,
                        };
                }

                return { isValid: true };
        }

        /**
         * Validates an email address
         *
         * @private
         * @param email - The email to validate
         * @returns Validation result with error message if invalid
         */
        private validateEmail(email: unknown): ValidationResult {
                if (typeof email !== 'string') {
                        return { isValid: false, error: 'Email must be a string' };
                }

                if (!CONFIG.EMAIL_REGEX.test(email)) {
                        return { isValid: false, error: 'Email format is invalid' };
                }

                return { isValid: true };
        }

        /**
         * Validates a phone number
         *
         * @private
         * @param phone - The phone number to validate
         * @returns Validation result with error message if invalid
         */
        private validatePhone(phone: unknown): ValidationResult {
                if (typeof phone !== 'string') {
                        return { isValid: false, error: 'Phone must be a string' };
                }

                if (phone.trim().length < 10) {
                        return { isValid: false, error: 'Phone number must have at least 10 digits' };
                }

                if (!CONFIG.PHONE_REGEX.test(phone)) {
                        return { isValid: false, error: 'Phone number contains invalid characters' };
                }

                return { isValid: true };
        }

        /**
         * Validates a person's age
         *
         * @private
         * @param age - The age to validate
         * @returns Validation result with error message if invalid
         */
        private validateAge(age: unknown): ValidationResult {
                if (typeof age !== 'number' || !Number.isInteger(age)) {
                        return { isValid: false, error: 'Age must be an integer' };
                }

                if (age < CONFIG.MIN_AGE) {
                        return { isValid: false, error: `Age must be at least ${CONFIG.MIN_AGE}` };
                }

                if (age > CONFIG.MAX_AGE) {
                        return { isValid: false, error: `Age cannot exceed ${CONFIG.MAX_AGE}` };
                }

                return { isValid: true };
        }

        /**
         * Adds a new person record to the data store
         *
         * Validates all input before insertion and assigns unique ID.
         *
         * @param name - Person's name
         * @param email - Person's email
         * @param phone - Person's phone number
         * @param age - Person's age
         * @returns Operation result with record ID on success
         *
         * @example
         * const result = store.addRecord('Alice', 'alice@example.com', '555-1234', 28);
         * if (result.status === OperationStatus.SUCCESS) {
         *   console.log(`Added record with ID: ${result.data}`);
         * }
         */
        addRecord(name: unknown, email: unknown, phone: unknown, age: unknown): OperationResult<number> {
                this.clearError();

                // Validate all inputs
                const nameValidation = this.validateName(name);
                if (!nameValidation.isValid) {
                        this.setError(nameValidation.error ?? 'Unknown error');
                        return {
                                status: OperationStatus.VALIDATION_ERROR,
                                error: nameValidation.error,
                        };
                }

                const emailValidation = this.validateEmail(email);
                if (!emailValidation.isValid) {
                        this.setError(emailValidation.error ?? 'Unknown error');
                        return {
                                status: OperationStatus.VALIDATION_ERROR,
                                error: emailValidation.error,
                        };
                }

                const phoneValidation = this.validatePhone(phone);
                if (!phoneValidation.isValid) {
                        this.setError(phoneValidation.error ?? 'Unknown error');
                        return {
                                status: OperationStatus.VALIDATION_ERROR,
                                error: phoneValidation.error,
                        };
                }

                const ageValidation = this.validateAge(age);
                if (!ageValidation.isValid) {
                        this.setError(ageValidation.error ?? 'Unknown error');
                        return {
                                status: OperationStatus.VALIDATION_ERROR,
                                error: ageValidation.error,
                        };
                }

                // Check storage capacity
                if (this.records.length >= this.maxRecords) {
                        const error = 'Record store is at maximum capacity';
                        this.setError(error);
                        return { status: OperationStatus.FAILURE, error };
                }

                // Create new record with type-safe data
                const newRecord = new PersonRecord({
                        id: this.nextId++,
                        name: (name as string).trim(),
                        email: (email as string).toLowerCase().trim(),
                        phone: (phone as string).trim(),
                        age: age as number,
                        isActive: true,
                });

                this.records.push(newRecord);
                this.isModified = true;

                console.log(`✓ Record added successfully with ID: ${newRecord.id}`);
                return { status: OperationStatus.SUCCESS, data: newRecord.id ?? 0 };
        }

        /**
         * Finds a record by its unique ID
         *
         * @param recordId - The ID to search for
         * @returns The found record or null if not found
         */
        findById(recordId: number): PersonRecord | null {
                return this.records.find(record => record.id === recordId) ?? null;
        }

        /**
         * Finds all records matching a name (case-insensitive partial match)
         *
         * @param name - The name to search for
         * @returns Array of matching records
         */
        findByName(name: string): PersonRecord[] {
                const searchTerm = name.toLowerCase().trim();
                return this.records.filter(record =>
                        record.name.toLowerCase().includes(searchTerm)
                );
        }

        /**
         * Finds a record by email address
         *
         * @param email - The email to search for
         * @returns The found record or null if not found
         */
        findByEmail(email: string): PersonRecord | null {
                const searchTerm = email.toLowerCase().trim();
                return this.records.find(record =>
                        record.email.toLowerCase() === searchTerm
                ) ?? null;
        }

        /**
         * Removes a record from the store by ID
         *
         * @param recordId - The ID of the record to remove
         * @returns Operation result
         */
        removeRecord(recordId: number): OperationResult<boolean> {
                const index = this.records.findIndex(record => record.id === recordId);

                if (index === -1) {
                        const error = `Record with ID ${recordId} not found`;
                        this.setError(error);
                        return { status: OperationStatus.NOT_FOUND, error };
                }

                const removedRecord = this.records.splice(index, 1)[0];
                this.isModified = true;

                console.log(`✓ Record removed: ${removedRecord.toString()}`);
                return { status: OperationStatus.SUCCESS, data: true };
        }

        /**
         * Returns all active records
         *
         * @returns Array of all active records
         */
        getAllRecords(): ReadonlyArray<PersonRecord> {
                return Object.freeze(this.records.filter(record => record.isActive));
        }

        /**
         * Gets the total count of records
         *
         * @returns Total number of records in store
         */
        getRecordCount(): number {
                return this.records.length;
        }

        /**
         * Gets the count of active records only
         *
         * @returns Number of active records
         */
        getActiveRecordCount(): number {
                return this.records.filter(record => record.isActive).length;
        }

        /**
         * Calculates the average age of all active records
         *
         * @returns Average age or 0 if no records
         */
        getAverageAge(): number {
                const activeRecords = this.records.filter(record => record.isActive);
                if (activeRecords.length === 0) return 0;

                const totalAge = activeRecords.reduce((sum, record) => sum + record.age, 0);
                return Math.round(totalAge / activeRecords.length);
        }

        /**
         * Exports all records as JSON array
         *
         * @returns Array of record objects in JSON format
         */
        exportAsJSON(): Array<Record<string, unknown>> {
                return this.records
                        .filter(record => record.isActive)
                        .map(record => record.toJSON());
        }

        /**
         * Displays all records in formatted table
         *
         * @returns void
         */
        displayAll(): void {
                const activeRecords = this.records.filter(record => record.isActive);

                if (activeRecords.length === 0) {
                        console.log('No records to display');
                        return;
                }

                console.log('\n========================================');
                console.log(`       ALL RECORDS (${activeRecords.length} total)`);
                console.log('========================================\n');

                activeRecords.forEach(record => {
                        console.log(`ID:     ${record.id}`);
                        console.log(`Name:   ${record.name}`);
                        console.log(`Email:  ${record.email}`);
                        console.log(`Phone:  ${record.phone}`);
                        console.log(`Age:    ${record.age}`);
                        console.log('---');
                });

                console.log('========================================\n');
        }
}

/**
 * =============================================================================
 * APPLICATION ENTRY POINT
 * =============================================================================
 */

/**
 * Main application function
 *
 * Demonstrates usage of the PersonDataStore with sample data
 *
 * @returns void
 */
function main(): void {
        console.log('=== Data Management System ===\n');

        // Initialize data store with type safety
        const store = new PersonDataStore({
                maxRecords: 1000,
        });

        // Define records with type safety
        interface PersonData {
                name: string;
                email: string;
                phone: string;
                age: number;
        }

        const records: PersonData[] = [
                { name: 'Alice Johnson', email: 'alice@example.com', phone: '555-1234', age: 28 },
                { name: 'Bob Smith', email: 'bob@example.com', phone: '555-5678', age: 35 },
                { name: 'Carol White', email: 'carol@example.com', phone: '555-9012', age: 32 },
                { name: 'David Brown', email: 'david@example.com', phone: '555-3456', age: 45 },
        ];

        console.log('Adding records...\n');