Generated Types
This guide explains how to work with and set up OpenAPI-generated types in a SAF monorepo.
Overview
The monorepo uses OpenAPI specifications housed in packages like @saflib/identity-spec
to generate TypeScript types that are shared between the service and client implementations. This ensures type safety across the entire application.
Example Package Structure
@saflib/identity-spec
: Contains the OpenAPI specification and generated types@saflib/auth-vue
: Consumes the generated types for client-side code@saflib/auth-node
: Consumes the generated types for server-side code (TODO)
Generation
Types, JSON, and HTML files are generated from OpenAPI YAML specifications. To do this, run:
bash
npm run generate
Using Generated Types
In Spec Packages
- Import types from the generated file:
typescript
import type { components, paths, operations } from "./dist/openapi.d.ts";
- Export specific types for consumers:
typescript
export type { paths, components, operations } from "./dist/openapi.d.ts";
// Re-export specific schema types
export type LoginRequest = components["schemas"]["LoginRequest"];
export type UserResponse = components["schemas"]["UserResponse"];
In Client Packages
- Import types from the spec package:
typescript
import type { components } from "@saflib/identity-spec";
// Use schema types
type LoginRequest = components["schemas"]["LoginRequest"];
- Use types with API clients:
typescript
import createClient from "openapi-fetch";
import type { paths } from "@saflib/identity-spec";
export const client = createClient<paths>({
baseUrl: `${document.location.protocol}//api.${document.location.host}`,
credentials: "include",
});
Best Practices
Type Exports
- Always export types through the package's main entry point
- Use type aliases for commonly used schema types
- Keep type exports focused and minimal
Type Imports
- Import from the package, not directly from generated files
- Use type imports to avoid runtime overhead
- Prefer importing specific types over entire namespaces
Type Updates
- Run type generation after updating OpenAPI specs
- Update dependent packages to use new types
- Test type changes across the monorepo
Common Issues
Missing Types
- Ensure types are generated
- Check package exports
- Verify import paths
Type Mismatches
- Keep API and client packages in sync
- Update types when changing API specs
- Run tests to catch type errors
Testing
When testing with OpenAPI types:
- Use type assertions sparingly
- Leverage TypeScript's type checking
- Mock API responses with correct types
- Test type safety in integration tests