JSON to TypeScript Discriminated Union — Result/Error Pattern
Convert json to typescript using a Result/Error discriminated union pattern. Replace try/catch returns with type-safe success and failure variants.
Detailed Explanation
Modeling Success and Failure as a Union
A traditional function either returns a value or throws. The Result pattern returns both possibilities as a single value, letting TypeScript force you to handle each branch.
Example JSON Samples
[
{ "type": "success", "data": { "id": 7, "name": "Alice" } },
{ "type": "error", "code": "NOT_FOUND", "message": "User does not exist" }
]
Generated TypeScript
interface Success {
type: "success";
data: {
id: number;
name: string;
};
}
interface Failure {
type: "error";
code: "NOT_FOUND" | "UNAUTHORIZED" | "RATE_LIMITED";
message: string;
}
type Result = Success | Failure;
Why a Discriminator Beats data | null
A nullable shape — { data: User | null; error: string | null } — forces every caller to write defensive null checks and still leaves { data: user, error: "boom" } representable. A discriminator (type) makes invalid combinations unrepresentable: each branch carries exactly the fields it needs.
Consuming the Type
function render(r: Result) {
if (r.type === "success") {
return r.data.name; // Success branch
}
return `[${r.code}] ${r.message}`; // Failure branch
}
The narrowing is exhaustive: if you later add a "pending" variant, every switch without a case for it becomes a compile error — provided you assert never in the default.
Generation Tips
When you feed both samples into a converter, mark type as a literal union. Keep data typed to its actual schema instead of unknown, and constrain code to a closed list of error codes you have seen in production. This produces a Result type that mirrors your real API and lets you delete defensive if (response.error) boilerplate.
Use Case
Wrapping fetch calls in a typed result so React components get exhaustive UI states for loading data, success, and a small enum of recoverable error codes.
Try It — JSON to TypeScript
Related Topics
Convert JSON to TypeScript Discriminated Union Types
Complex Types
Convert Stripe Charge JSON to TypeScript Interfaces
Real-World API Schemas
Convert GitHub Repository API JSON to TypeScript
Real-World API Schemas
Type a Generic Webhook Payload in TypeScript
Real-World API Schemas
Convert JSON:API Spec Responses to TypeScript
Real-World API Schemas