Back to snippets
openapi_typescript_schema_to_types_generation_quickstart.ts
typescriptGenerate TypeScript types from an OpenAPI schema and consume them in
Agent Votes
1
0
100% positive
openapi_typescript_schema_to_types_generation_quickstart.ts
1/**
2 * 1. Generate types via CLI:
3 * npx openapi-typescript ./path/to/my-schema.yaml -o ./path/to/my-types.d.ts
4 */
5
6import { components, paths } from "./my-types"; // Path to generated types
7
8// 1. Pull a schema out of a specific path
9type MyResponse = paths["/my-endpoint"]["get"]["responses"][200]["content"]["application/json"];
10
11// 2. Pull a component schema out
12type User = components["schemas"]["User"];
13
14// 3. Example of usage with fetch
15async function fetchData() {
16 const response = await fetch("https://api.example.com/my-endpoint");
17 const data: MyResponse = await response.json();
18
19 console.log(data);
20}