> ## Documentation Index
> Fetch the complete documentation index at: https://system.muzemus.online/llms.txt
> Use this file to discover all available pages before exploring further.

# Type safety

> TypeScript patterns, Prisma-generated types, and Zod schemas

## Type safety layers

```mermaid theme={null}
flowchart LR
    A[Database schema] -->|Prisma generate| B[Prisma types]
    B -->|DTO validation| C[class-validator DTOs]
    A -->|API responses| D[Frontend domain types]
    D -->|Form validation| E[Zod schemas]
    E -->|Forms| F[React Hook Form]
```

## Backend type safety

### Prisma-generated types

Prisma generates TypeScript types from the schema:

```typescript theme={null}
import { Prisma, Order } from '@prisma/client';

const order: Order = await prisma.order.findUnique({ where: { id } });

type OrderWithItems = Prisma.OrderGetPayload<{
  include: { items: true; employee: true };
}>;
```

### DTO validation

Request DTOs use `class-validator` decorators with TypeScript classes:

```typescript theme={null}
export class CreateOrderDto {
  @IsString()
  @IsNotEmpty()
  employeeId: string;

  @IsArray()
  @ValidateNested({ each: true })
  @Type(() => CreateOrderItemDto)
  items: CreateOrderItemDto[];
}
```

The global `ValidationPipe` enforces these DTOs on every request (see [Validation](/security/validation)).

### Request types

The request object is extended with auth context:

```typescript theme={null}
export interface RequestWithPermissions extends Request {
  auth: { session: Session; user: User };
  userRoles: UserRoleScope[];
  permissions: Permission[];
  isAdmin: boolean;
}
```

### Environment validation

Startup environment variables are validated with a Zod schema in `backend/src/config/env.validation.ts`. An invalid environment fails the boot.

## Frontend type safety

### API response types

`src/lib/domain-types.ts` is the canonical frontend source of truth for REST response shapes (`Client`, `Store`, `Employee`, `RuleSet`, report types), with order-lifecycle types in `src/lib/types.ts`:

```typescript theme={null}
export interface Order {
  id: string;
  orderNumber: string;
  status: OrderStatus;
  employee: Employee;
  items: OrderItem[];
  createdAt: string;
}
```

### Zod schemas

Forms validate with Zod schemas through React Hook Form resolvers:

```typescript theme={null}
const createOrderSchema = z.object({
  employeeId: z.string().uuid(),
  items: z.array(z.object({
    productId: z.string().uuid(),
    quantity: z.number().int().min(1),
    size: z.string().min(1),
  })).min(1),
});

const form = useForm<CreateOrderInput>({
  resolver: zodResolver(createOrderSchema),
});
```

## Enum sharing

Enums exist as Prisma enums on the backend and mirrored string-literal unions on the frontend:

```typescript theme={null}
type OrderStatus =
  | 'PENDING_APPROVAL'
  | 'SUBMITTED'
  | 'APPROVED'
  // ... 12 values mirroring the Prisma enum
```

The frontend's status registry (`src/lib/order-status.ts`, `src/lib/status.ts`) derives labels and treatments from these unions so the UI can never display an unmapped status.

## Strict TypeScript settings

Backend `tsconfig.json` enables `strict` plus `noUncheckedIndexedAccess`, `noImplicitReturns`, and `noFallthroughCasesInSwitch`. The frontend enables `strict` with the `@/*` path alias mapped to `./src/*`.

Production code carries zero avoidable `any` and zero `@ts-ignore` directives; test mocks are the only relaxed area.

## Known gaps

| Gap                                    | Impact                                                        |
| -------------------------------------- | ------------------------------------------------------------- |
| Frontend types manually maintained     | Can drift from backend DTOs; caught at compile time via `tsc` |
| No runtime validation of API responses | Invalid data could reach components unvalidated               |
| No shared type package                 | Types duplicated between backend and frontend                 |
