TypeScript Union Types: Extract & Exclude

'Pick' and 'Omit' are great for objects. But what about union types? If you’ve used 'Pick' and 'Omit' before, you already understand one important idea in TypeScript - 'We can derive new types from existing ones instead of rewriting them.' But 'Pick' and 'Omit' only work on object shapes. What happens when you’re working with union types instead? That’s exactly where 'Extract' and 'Exclude' come in. Think of them as filters for union types. While 'Pick' and 'Omit' operate on keys of objects, 'Extract' and 'Exclude' operate on members of union types. Conceptually, 'Extract' keeps what matches & 'Exclude' removes what matches. So, when you write 'Extract<A, B>', it means 'From union A, keep only the members that are assignable to B.' Similarly, when you write 'Exclude<A,B>', it means 'From union A, remove anything that is assignable to B.' These utility types shine when your codebase grows. They help you avoid duplicating unions, and keep types in sync automatically. If the original union evolves, your derived types evolve with it. No manual updates needed. #TypeScript #JavaScript #WebDevelopment #Programming #SoftwareEngineering

  • text

To view or add a comment, sign in

Explore content categories