DEV Community

Discussion on: Stop Pretending The Error Never Happened! Be Explicit About Loading State

Collapse
 
rensjaspers profile image
Rens Jaspers • Edited

Shoutout to @simonjaspers for suggesting the use of a union type for the loading state, instead of a single type with optional error and data properties.

This trick prevents you from creating nonsensical loading states. For example, the TypeScript compiler will helpfully throw an error if you try to create a state like { state: "loading", error: error }, as you can’t be in a loading and hold an error value at the same time.

The union type also makes writing templates easier, as TypeScript can figure out which variant of the union type is being referenced with each @switch(emails.state) case.

For @case("loading"), intellisense will tell you that the object won't have data or error properties, and for @case("loaded"), it understands that there will be data but there will be no error value. So trying to access {{emails.error.message}} in the template under @case("loaded") will throw a compilation error. :-)