TypeScript · Middle · Question 37 of 75

What's the best way to type an API response whose structure differs by status?

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.

Further reading

Problem with a question

TypeScript · Middle · question 37

Test yourself

Take the TypeScript · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz