emr-types
Version:
Comprehensive TypeScript Types Library for Electronic Medical Record (EMR) Applications - Domain-Driven Design with Zod Validation
376 lines (292 loc) โข 9.5 kB
Markdown
# emr-types
[](https://badge.fury.io/js/%40qkit-emr-monorepo%2Ftypes)
[](https://opensource.org/licenses/MIT)
[](https://www.typescriptlang.org/)
> Comprehensive TypeScript Types Library for Electronic Medical Record (EMR) Applications
A comprehensive, type-safe TypeScript library for Electronic Medical Record (EMR) applications. Built with Domain-Driven Design principles, featuring robust type safety, runtime validation with Zod, and excellent developer experience.
## ๐ Features
- **๐ฅ Healthcare Focus**: Complete types for medical records, patients, appointments, and healthcare standards
- **๐ก๏ธ Type Safety**: 100% TypeScript strict mode compliance with branded types
- **โ
Runtime Validation**: Comprehensive Zod schema validation for all types
- **๐ Form System**: Type-safe form handling with validation
- **โฐ Date/Time**: Healthcare-specific date/time management
- **๐๏ธ Domain-Driven Design**: Clear domain boundaries and aggregate roots
- **๐ง Utilities**: Form, validation, and date/time utilities
- **๐ Performance**: Optimized bundle size and compilation
## ๐ฆ Installation
```bash
npm install emr-types
```
```bash
yarn add emr-types
```
```bash
pnpm add emr-types
```
## ๐ฅ Healthcare Standards Support
- **ICD-10/11**: International Classification of Diseases codes
- **CPT/HCPCS**: Current Procedural Terminology codes
- **NDC/RxNorm**: National Drug Codes and RxNorm
- **LOINC**: Logical Observation Identifiers Names and Codes
- **HIPAA**: Health Insurance Portability and Accountability Act compliance
## ๐ฏ Quick Start
### Basic Usage
```typescript
import {
User,
UserRole,
UserStatus,
validateSchema,
UserSchemas
} from 'emr-types';
// Create a user with type safety
const user: User = {
id: 'user-123' as any, // Branded type
email: 'doctor@hospital.com',
firstName: 'John',
lastName: 'Doe',
role: 'doctor',
status: 'active',
tenantId: 'tenant-123' as any,
createdAt: new Date(),
updatedAt: new Date()
};
// Validate data at runtime
const userData = {
email: 'doctor@hospital.com',
firstName: 'John',
lastName: 'Doe',
role: 'doctor',
tenantId: 'tenant-123'
};
const result = validateSchema(UserSchemas.CreateUserRequest, userData);
if (result.success) {
console.log('Valid user data:', result.data);
} else {
console.log('Validation errors:', result.errors);
}
```
### Form Handling
```typescript
import {
FormField,
FormFieldType,
FormState,
createFormValidator,
UserSchemas
} from 'emr-types';
// Create type-safe form fields
const userForm: FormField[] = [
{
name: 'email',
label: 'Email',
type: FormFieldType.EMAIL,
value: '',
required: true
},
{
name: 'firstName',
label: 'First Name',
type: FormFieldType.TEXT,
value: '',
required: true
}
];
// Create form validator
const validateUserForm = createFormValidator(UserSchemas.CreateUserRequest);
// Form state management
const formState: FormState = {
values: { email: '', firstName: '' },
errors: {},
touched: {},
dirty: {},
focused: {},
isValid: false,
isDirty: false,
isSubmitting: false,
isSubmitted: false,
submitCount: 0
};
```
### Date/Time Management
```typescript
import {
calculateAge,
calculateDuration,
isInBusinessHours,
AppointmentTimeSlot
} from 'emr-types';
// Calculate patient age
const birthDate = new Date('1990-01-01');
const age = calculateAge(birthDate);
console.log(`Patient age: ${age.years} years, ${age.months} months`);
// Appointment time slot
const appointment: AppointmentTimeSlot = {
start: new Date('2024-01-01T09:00:00Z'),
end: new Date('2024-01-01T10:00:00Z'),
duration: 60,
isAvailable: true,
isBooked: false
};
// Check business hours
const businessHours = {
start: '09:00',
end: '17:00',
daysOfWeek: [1, 2, 3, 4, 5], // Monday to Friday
timezone: 'America/New_York'
};
const isAvailable = isInBusinessHours(appointment.start, businessHours);
```
## ๐๏ธ Architecture
### Domain-Driven Design
The library follows Domain-Driven Design principles with clear bounded contexts:
- **User Domain**: User management, roles, and authentication
- **Tenant Domain**: Multi-tenant support and configuration
- **Patient Domain**: Patient management and medical history
- **Appointment Domain**: Appointment scheduling and management
- **Medical Record Domain**: Medical records, diagnoses, and procedures
- **Shared Domain**: Common types and utilities
### Type Safety
- **Branded Types**: Secure ID types with branded strings
- **Union Types**: Flexible union types for enums and status values
- **Generic Types**: Comprehensive generic type system
- **Conditional Types**: Advanced conditional type logic
### Runtime Validation
- **Zod Schemas**: Complete schema definitions for all types
- **Custom Validation**: Healthcare-specific validation rules
- **Error Handling**: Detailed error messages and field-specific errors
- **Batch Validation**: Batch validation capabilities
## ๐ API Reference
### Core Types
```typescript
// User Domain
import { User, UserRole, UserStatus } from 'emr-types';
// Tenant Domain
import { Tenant, TenantType, TenantStatus } from 'emr-types';
// Patient Domain
import { Patient, Gender, BloodType } from 'emr-types';
// Appointment Domain
import { Appointment, AppointmentType, AppointmentStatus } from 'emr-types';
// Medical Record Domain
import { MedicalRecord, Diagnosis, Prescription } from 'emr-types';
```
### Validation
```typescript
import {
validateSchema,
safeParse,
isValid,
UserSchemas,
TenantSchemas,
PatientSchemas
} from 'emr-types';
// Validate user data
const result = validateSchema(UserSchemas.CreateUserRequest, userData);
// Safe parse with error handling
const parsed = safeParse(UserSchemas.User, userData);
// Quick validation check
const isValidUser = isValid(UserSchemas.User, userData);
```
### Form Utilities
```typescript
import {
FormField,
FormState,
FormFieldType,
createFormValidator,
isFormValid,
isFormDirty
} from 'emr-types';
// Create form validator
const validateForm = createFormValidator(UserSchemas.CreateUserRequest);
// Check form state
const isValid = isFormValid(formState);
const isDirty = isFormDirty(formState);
```
### Date/Time Utilities
```typescript
import {
calculateAge,
calculateDuration,
toISODateString,
parseISODateString,
isInBusinessHours
} from 'emr-types';
// Age calculation
const age = calculateAge(birthDate);
// Duration calculation
const duration = calculateDuration(startDate, endDate);
// ISO date handling
const isoDate = toISODateString(date);
const parsedDate = parseISODateString('2024-01-01');
```
## ๐งช Testing
### Type Testing
```typescript
import { expectType } from 'tsd';
import { User, UserRole } from 'emr-types';
// Test type inference
expectType<User>({
id: 'user-123' as any,
email: 'user@example.com',
firstName: 'John',
lastName: 'Doe',
role: 'admin',
status: 'active',
tenantId: 'tenant-123' as any,
createdAt: new Date(),
updatedAt: new Date()
});
// Test enum values
expectType<UserRole>('admin');
```
### Runtime Testing
```typescript
import { UserSchemas, validateSchema } from 'emr-types';
describe('User Validation', () => {
it('should validate valid user data', () => {
const userData = {
email: 'user@example.com',
firstName: 'John',
lastName: 'Doe',
role: 'doctor',
tenantId: 'tenant-123'
};
const result = validateSchema(UserSchemas.CreateUserRequest, userData);
expect(result.success).toBe(true);
});
});
```
## ๐ Performance
- **Bundle Size**: <50KB gzipped
- **Compilation Time**: <10 seconds
- **Type Inference**: >98% accuracy
- **IDE Performance**: <5% impact
## ๐ค Contributing
We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
### Development Setup
```bash
# Clone the repository
git clone https://github.com/qkit-emr/emr-monorepo.git
cd emr-monorepo/libs/types
# Install dependencies
npm install
# Run type checking
npm run typecheck
# Run tests
npm test
# Build the library
npm run build
```
## ๐ License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## ๐ Support
- **Documentation**: [API Documentation](https://github.com/qkit-emr/emr-monorepo/tree/main/libs/types/docs)
- **Issues**: [GitHub Issues](https://github.com/qkit-emr/emr-monorepo/issues)
- **Discussions**: [GitHub Discussions](https://github.com/qkit-emr/emr-monorepo/discussions)
## ๐ Related
- [EMR Monorepo](https://github.com/qkit-emr/emr-monorepo) - Full EMR application
- [Zod](https://zod.dev/) - TypeScript-first schema validation
- [Domain-Driven Design](https://martinfowler.com/bliki/DomainDrivenDesign.html) - Software design approach
---
**Built with โค๏ธ by the QKIT EMR Team**