JSON से TypeScript: Interface definitions हाथ से लिखना बंद करें

2024-08-04

हाथ से लिखे interfaces अक्सर real API responses से अलग हो जाते हैं। Sample JSON से types generate करना standard practice है—बस rules और limitations समझें.

Types generate क्यों करें?

Compile-time पर typos और null access errors पकड़ने में मदद मिलती है, खासकर जब OpenAPI missing या outdated हो.

Manual mapping example

JSON
{ "id": 1, "name": "Alice", "email": null }
TypeScript
interface User {
  id: number;
  name: string;
  email: string | null;
}

Nested arrays और unions

Empty arrays के लिए manual element type चाहिए; heterogeneous arrays अक्सर union types बनाती हैं.

Optional बनाम null

Missing key (email?) और null value (email: string | null) अलग semantics हैं; backend contract के अनुसार choose करें.

Tools

quicktype CLI, json-schema-to-typescript, और one-off tasks के लिए online json2ts उपयोगी हैं.

# npx quicktype sample.json -o types.ts --lang typescript

Best practices

Generated files manually edit करने के बजाय regenerate करें, multiple samples दें, और breaking API changes पकड़ने के लिए tsc चलाएं.