Q50. How do you safely model API success and failure?

A discriminated union such as { ok: true; data: T } | { ok: false; error: E } represents mutually exclusive outcomes. Consumers can branch on ok and get the corresponding data or error type. Runtime code must still construct the correct variant.

The discriminant makes it impossible to accidentally treat the error branch as though it contains successful data without a check.

Note

Interview approach: define the concept, explain why it matters, then mention one trade-off or limitation.

TypeScript concept
// Illustrative TypeScript contract
type Identifier = string;
const id: Identifier = "item-1";
💡 The example demonstrates the compile-time contract discussed in this question.
Key Takeaways
  • Explain the concept in your own words.
  • Know the practical trade-off and its limits.
  • Use a small example to demonstrate the idea.
Knowledge Check

What is the benefit of a discriminant like `ok: true | false`?