
The most powerful pattern in TypeScript, Discriminated Unions
Discriminated Unions is useful in cases where you have a discriminant, which is a common property with a literal type (like 'idle', 'loading') that exists in every member. 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 creat
Continue reading on Dev.to
Opens in a new tab

