Type-safe extraction with compile-time validation
Quick Answer
`StrictExtract<T, U extends T>` is a drop-in replacement for `Extract` that errors at compile time if U is not actually a member of T.
1type StrictExtract<T, U extends T> = Extract<T, U>;
2
3// Usage
4type Status = 'pending' | 'approved' | 'rejected';
5type PositiveStatus = StrictExtract<Status, 'approved'>;
6
7// This will error at compile time
8// type Invalid = StrictExtract<Status, 'invalid'>;The built-in Extract<T, U> silently returns never if U is not a member of T, which hides typos and mistakes. StrictExtract adds a constraint (U extends T) so that attempting to extract a value that does not exist in the union produces a compile-time error immediately.
Use StrictExtract when deriving a sub-union programmatically from a base union type you do not own. Use a direct type annotation when the sub-union is stable and small enough to write out by hand.
This free typescript code snippet for strict extract type is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this intermediate-level example will help you implement strict extract type quickly and correctly.
All snippets in the Snippetly library follow typescript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses typescript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.