๐—ง๐˜†๐—ฝ๐—ฒ๐—ฆ๐—ฐ๐—ฟ๐—ถ๐—ฝ๐˜ ๐—จ๐˜๐—ถ๐—น๐—ถ๐˜๐˜† ๐—ง๐˜†๐—ฝ๐—ฒ๐˜€: ๐—›๐—ผ๐˜„ ๐—ง๐—ต๐—ฒ๐˜† ๐—ช๐—ผ๐—ฟ๐—ธ

Most TypeScript developers use Pick, Omit, Partial, and Record every day.

Few know how they work under the hood.

When you understand the logic, three things change:

Everything in TypeScript builds from two core primitives: Mapped Types and Conditional Types.

โ€ข Mapped Types: These iterate over object keys to transform them. โ€ข Conditional Types: These select between two types based on a condition.

Here is a breakdown of the most important utilities:

Partial Makes every property optional. It uses a mapped type with a "?" modifier. Use this for PATCH endpoints or configuration updates.

Required The inverse of Partial. It makes every property mandatory. It uses the "-?" syntax to strip the optional modifier.

Readonly Marks every property as read-only. Use this to freeze configuration objects.

Pick<T, K> Creates a new type using only specific keys from an existing type. The K parameter must exist in T to prevent typos.

Omit<T, K> The inverse of Pick. It removes specific keys from a type. It works by combining Pick and Exclude.

Record<K, T> Builds an object type from scratch. K defines the keys and T defines the values. This is perfect for mapping enums to data.

Exclude<T, U> Removes members from a union. If a member in T matches U, it is removed.

Extract<T, U> The inverse of Exclude. It keeps only the members of a union that match a specific shape.

Parameters and ReturnType These use the "infer" keyword. They extract the argument types or the return type from a function.

NonNullable Removes null and undefined from a type.

Pro tips for better code:

TypeScript utilities are not magic. They are just organized logic. If you get stuck, use Cmd+Click in VS Code to read the actual definition.

Source: https://dev.to/kaithorne/typescript-utility-types-how-they-work-not-just-what-they-do-4bc1