Useful TypeScript utility type definitions
Quick Answer
TypeScript utility types like `Partial<T>`, `Pick<T,K>`, and `Omit<T,K>` derive new types from existing ones — eliminating manual interface duplication.
1// Make all properties optional recursively
2type DeepPartial<T> = {
3 [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
4};
5
6// Make specific keys required
7type RequireKeys<T, K extends keyof T> = T & Required<Pick<T, K>>;
8
9// Extract keys of specific type
10type KeysOfType<T, U> = {
11 [K in keyof T]: T[K] extends U ? K : never;
12}[keyof T];TypeScript ships with useful built-in utility types (Partial, Readonly, Pick, etc.) but some common patterns require custom implementations. These helpers — DeepPartial for recursive optional fields, RequireKeys for making specific fields required, and KeysOfType for filtering keys by value type — cover the most frequently needed advanced scenarios.
`Pick<T, K>` whitelists the keys you want to keep. `Omit<T, K>` blacklists the keys you want to remove. Use Pick when the keep-list is short; use Omit when the remove-list is short.
This free typescript code snippet for utility types is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this advanced-level example will help you implement utility types 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.