Using TypeScript Effectively for Business Front‑End Development with OpenAPI and Code Generation
This article explains why TypeScript is suitable for business front‑end code, demonstrates practical usage with React, SWR, and OpenAPI, and shows how to generate type definitions automatically using openapi‑typescript to improve robustness and maintainability.
In recent community discussions many claim that typescript is unsuitable for business code, but this article argues that, when used correctly, TypeScript greatly enhances robustness and maintainability of front‑end applications.
Using a typical Form/Table page as an example, the article shows how query parameters such as page , size , and filter are stored in a deps object; changing this object triggers a useEffect data request. When libraries like swr or react‑query are used, the dependency should be a key instead.
An illustrative SWR example fetches a list endpoint, defining ListParams and ListOutput types so that TypeScript can perform static type checking and provide IntelliSense, preventing parameter mismatches and undefined‑property errors.
The article then introduces OpenAPI (formerly Swagger) as a machine‑readable interface definition language. If a backend follows the OpenAPI spec, a Swagger document can be used to generate TypeScript types automatically.
To generate types, the author recommends the openapi-typescript tool (v5.4.1). After installing with yarn add -D [email protected] , a script is added to package.json :
"scripts": { "codegen": "npx openapi-typescript
--c .prettierrc.js --make-paths-enum --output ./src/ApiInterface.ts" }Running yarn codegen generates an ApiInterface.ts file containing enums for paths and schema types under components.schemas . The generated enums prevent hard‑coded path errors, and the schema types can be re‑exported, e.g.:
import { type components } from '@/ApiInterface';
export type ApiInterface = components['schemas'];This approach eliminates manual type definitions; when the backend changes, re‑running the codegen updates the types and the editor highlights required code adjustments, making TypeScript business development pleasant.
In summary, although this method is not as seamless as tRPC’s direct type reuse, it offers a low‑cost, widely applicable solution for projects that adhere to OpenAPI, allowing front‑end teams to enjoy the safety and productivity benefits of TypeScript.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.