When working with TypeScript types, the design of our types is important. One choice we often see is to define an interface, but many times a union is preferable to a single interface. Here are two types that can be used in similar ways, below I’ll explain why the union is often preferable:
interface SessionDataMega { isLoggedIn: boolean; user?: { name: string }; }type SessionDataUnion = | { isLoggedIn: false; user?: never; } | { isLoggedIn: true; user: { name: string }; };SessionDataMega is a wider type. It’s flexible enough to cover all the different shapes of data we expect — and some we don’t!
SessionDataUnion is a union of two narrower types. The union consists of two types (members of the union) that are both more specific than the interface.