TypeScript · Middle · Question 37 of 75
What's the best way to type an API response whose structure differs by status?
- ✓Correct answer: A union discriminated by
ok: success withdataor an error - 2One shared type with all fields made optional
- 3The
anytype, because the response structure isn't known in advance
Explanation
A union makes impossible states unrepresentable: with ok: true, data is guaranteed and error isn't available. A type with optional fields allows meaningless combinations and requires checks everywhere.