๐ง๐๐ฝ๐ฒ๐ฆ๐ฐ๐ฟ๐ถ๐ฝ๐ ๐จ๐๐ถ๐น๐ถ๐๐ ๐ง๐๐ฝ๐ฒ๐: ๐๐ผ๐ ๐ง๐ต๐ฒ๐ ๐ช๐ผ๐ฟ๐ธ
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:
- You stop guessing which utility to use.
- You combine them to solve complex problems.
- You write your own custom types when built-ins fail.
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
Required
Readonly
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
NonNullable
Pro tips for better code:
- Use DeepPartial for nested objects. The built-in version is shallow.
- Use Readonly<Partial
> for immutable configurations. - Use PickByValue to select keys based on their data type rather than their name.
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