TS TypeScript4 / 4
Utility Types
📌 WHAT
Built-in TypeScript types that transform existing types into new ones. They save you from manually writing common type transformations.
💡 WHY
Avoid rewriting type definitions. Make your types expressive and correct. Express intent clearly: 'this is a partial User' vs redeclaring everything as optional.
⏰ WHEN / WHERE
Frequently in real projects: form types, API endpoints, component props variations, state management.
🔧 HOW
Use as generic wrappers around existing types: Partial<User>, Pick<User, 'id' | 'name'>, etc.
Code Examples
#1The most useful utility types
The most useful utility types
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
interface User {id: number;name: string;email: string;role: "admin" | "user";createdAt: Date;}// Partial<T> — all properties become optional// Perfect for UPDATE operations where you only send changed fieldstype UserUpdate = Partial<User>;// { id?: number; name?: string; email?: string; ... }async function updateUser(id: number, changes: Partial<User>) {// changes might only have { name: "New Name" }}// Required<T> — all optional become requiredtype RequiredUser = Required<User>; // removes all ?// Pick<T, Keys> — select specific propertiestype UserPreview = Pick<User, "id" | "name">;// { id: number; name: string }// Omit<T, Keys> — exclude specific propertiestype UserWithoutDates = Omit<User, "createdAt">;// { id, name, email, role } — no createdAttype NewUser = Omit<User, "id" | "createdAt">;// { name, email, role } — for creating new user (no id yet)// Record<Keys, Type> — object with specific key/value typestype RolePermissions = Record<"admin" | "user", string[]>;const permissions: RolePermissions = {admin: ["read", "write", "delete"],user: ["read"],};// ReturnType<T> — extract return type of functionasync function getUser() { return { id: 1, name: "Ali" }; }type FetchedUser = Awaited<ReturnType<typeof getUser>>;// { id: number; name: string }// Readonly<T> — prevent mutationtype ReadonlyUser = Readonly<User>;const frozen: ReadonlyUser = { id: 1, name: "Ali", /* ... */ };// frozen.name = "X"; // ❌ Error: cannot assign to readonly property
Practice This Concept
Open the playground, paste any example, and experiment. The best way to learn is by breaking things.
Open in Playground