The most powerful patterns in TypeScript. **Discriminated Unions**
=== Most useful in cases where you have known result with list of known attribute value. TypeScript will narrow the type based on the discriminator, a common property to discriminate between union ...

Source: DEV Community
=== Most useful in cases where you have known result with list of known attribute value. TypeScript will narrow the type based on the discriminator, a common property to discriminate between union members. , making your code much safer. type State = | { status: 'idle' } | { status: 'loading' } | { status: 'success'; data: string } | { status: 'error'; error: Error } function handleState(state: State) { switch (state.status) { case 'idle': // TypeScript knows state is { status: 'idle' } break case 'loading': // TypeScript knows state is { status: 'loading' } break case 'success': // TypeScript knows state has 'data' property console.log(state.data.toUpperCase()) break case 'error': // TypeScript knows state has 'error' property console.error(state.error.message) break } } The most powerful patterns in TypeScript. Discriminated Unions allow you to create a type-safe state machine where the compiler ensures you only access data that actually exists in a given state. Here is a breakdown of