Generic Constraint With Conditional Type
Use generic constraints and conditional types for type-safe utility functions with compile-time checks.
Code
export function pick<T extends object,K extends keyof T>(obj:T,keys:K[]):Pick<T,K>{const result={} as Pick<T,K>;for(const k of keys)result[k]=obj[k];return result;}export function omit<T extends object,K extends keyof T>(obj:T,keys:K[]):Omit<T,K>{const result={...obj};for(const k of keys)delete result[k];return result;}export type DeepPartial<T>={[K in keyof T]?:T[K]extends object?DeepPartial<T[K]>:T[K]};export type NonEmptyArray<T>=[T,...T[]];export function first<T extends NonEmptyArray<unknown>>(arr:T):T[number]{return arr[0];}What to watch for
pick is bounded twice: T extends object rejects primitives, and K extends keyof T means every entry of keys must name a real property, so a misspelled key fails at compile time. The return type Pick<T, K> keeps only the chosen keys — the loop assigns result[k] = obj[k] for each requested key and returns the narrowed object.
omit is the mirror image: it spreads the whole object and deletes the listed keys, typed as Omit<T, K> so the result excludes exactly those names. DeepPartial<T> is where the conditional type does the work — [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K] recurses into nested objects and leaves primitives as plain optionals.
The last pair encodes a runtime assumption in the type system: NonEmptyArray<T> is defined as [T, ...T[]], so first only accepts arrays the compiler knows are non-empty, and arr[0] can return T[number] without an undefined branch.
Interactive Tools for This Topic
FAQ
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used.
Report a problem with this exampleOpens a pre-filled issue on GitHub.