Module lessons (2/2)
Unions and Shrinkage
Combine union types, check cases with typeof/in, and design safe discriminated unions.
What you'll learn in this lesson
- Combine as many types as possible using
|(string | number,'loading' | 'success' | 'error'). - Understand why TypeScript only allows common members on a union before type narrowing.
- Naturally apply the built-in guards:
typeof,== null,inoperator and literal equality check. - Design robust Discriminated Unions by checking for completeness with
never.
Overview
In the real world, a function often receives values that can take different forms: a textual or numeric ID, or the status of a network call (loading, success, error). In TypeScript they are modeled with union types (A | B).
Before you demonstrate which variant you have in your hands, TypeScript lets you read only what belongs to all members of the union. As soon as you write a guard if, control flow analysis automatically narrows the type within that branch.
Sections covered in this lesson
- 1Guards integrated into flow control
- 2Discriminated Unions: the main pattern of TypeScript
- 3Guided practice
- 4Check for understanding
Unlock "Unions and Shrinkage" and the full Course TypeScript curriculum
Combine union types, check cases with typeof/in, and design safe discriminated unions.
Unlock all 6 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course TypeScript plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.