Back to Snippets
TypeScriptTypeScript

TypeScript Utility Types

Useful custom utility types for everyday TypeScript development.

typescripttypesutilitygeneric
class=class="text-emerald-400">"text-gray">// Make specific keys optional
type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>

class=class="text-emerald-400">"text-gray">// Make specific keys required
type RequiredBy<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>

class=class="text-emerald-400">"text-gray">// Deep partial — all nested properties become optional
type DeepPartial<T> = {
  [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P]
}

class=class="text-emerald-400">"text-gray">// Extract non-nullable values from an object type
type NonNullableFields<T> = {
  [P in keyof T]: NonNullable<T[P]>
}

class=class="text-emerald-400">"text-gray">// Create a type from an arrayclass=class="text-emerald-400">"text-emerald-400">'s values
const ROLES = ['adminclass=class="text-emerald-400">"text-emerald-400">', 'editorclass=class="text-emerald-400">"text-emerald-400">', 'viewerclass=class="text-emerald-400">"text-emerald-400">'] as const
type Role = (typeof ROLES)[number] class=class="text-emerald-400">"text-gray">// 'adminclass=class="text-emerald-400">"text-emerald-400">' | 'editorclass=class="text-emerald-400">"text-emerald-400">' | 'viewer'

class=class="text-emerald-400">"text-gray">// Strongly-typed Object.keys
function typedKeys<T extends object>(obj: T): (keyof T)[] {
  return Object.keys(obj) as (keyof T)[]
}

How to Use

Use PartialBy when creating forms where some fields are optional: type CreateUser = PartialBy<User, 'id' | 'createdAt'>. Use DeepPartial for patch operations on nested objects.

Related Technology

TypeScript

Have a Project in Mind?

Let's discuss how we can bring your idea to life. From initial concept to production-ready product — we've got you covered.

or book a free call