Generating TypeScript types from a Swagger (OpenAPI) specification and using them in your codebase offers several advantages compared to manually typing them:
- Accuracy and Consistency: When you generate TypeScript types from a Swagger specification, you ensure that the types are accurate and consistent with the API definition. This helps prevent errors that might arise from manually typing types that don’t match the actual API endpoints, request, and response structures.
- Reduced Duplication: By generating types, you eliminate the need to manually replicate the API structure in your TypeScript code. This reduces the chances of inconsistencies and saves time since changes in the API can be reflected directly by regenerating the types.
- Efficiency: Generating types automates a typically repetitive and error-prone task. This speeds up development and decreases the likelihood of introducing typing mistakes, particularly in complex APIs with numerous endpoints and data models.
- Maintainability: As the API evolves, maintaining manually typed types can be cumbersome. With generated types, updates to the API are easier to manage, as you can simply regenerate the types from the updated Swagger specification.
- Less Prone to Human Errors: Manually typing types can lead to typos, incorrect field names, mismatched data structures, and other human errors. Generated types are derived directly from the API specification, minimizing these risks.
- Version Compatibility: When the API undergoes changes, the generated types can help identify areas of your code that need adjustment due to breaking changes. This can save time during the migration process.
While generating TypeScript types from a Swagger specification provides numerous benefits, it’s essential to note that there might be cases where manual typing is more appropriate. For instance, if you need to introduce custom logic or additional validation in your TypeScript types, manual typing might be preferred. However, in general, generating types from a Swagger specification is a powerful tool to streamline API integration and reduce potential errors.
For generating the TypeScript interfaces from a Swagger specification we use this package:
https://www.npmjs.com/package/swagger-typescript-api
After installing the package, the types can be genereted using the following command
npx swagger-typescript-api -p [url-to-swagger] -o [output] -n [name] --no-client
Example
npx swagger-typescript-api -p https://petstore.swagger.io/v2/swagger.json -o ./src/types -n apiTypes.ts --no-client
This will generated types using the “https://petstore.swagger.io/v2/swagger.json” Swagger JSON and output the types into ./src/types in a file called apiTypes.ts. We added the –no-client parameter here because in this case we do not want to generate any clients, just the types.