TypeScript Utility Types

TypeScript tutorial

🧰 TypeScript Utility Types

TypeScript Utility Types are built-in TypeScript helpers that transform existing types instead of rewriting them.

They make your code cleaner, safer, and more maintainable—especially in real projects.


1️⃣ Partial<T>

Makes all properties optional.

type User = {
id: number;
name: string;
email: string;
};
type UpdateUser = Partial<User>;

let data: UpdateUser = {
email: “new@mail.com”
};

📌 Used in update APIs


2️⃣ Required<T>

Makes all properties required.

type UserOptional = {
id?: number;
name?: string;
};
type UserRequired = Required<UserOptional>;


3️⃣ Readonly<T>

Makes all properties immutable.

type Product = {
id: number;
price: number;
};
const item: Readonly<Product> = {
id: 1,
price: 500
};

// item.price = 600 ❌ Error


4️⃣ Pick<T, K>

Select specific properties from a type.

type UserPreview = Pick<User, "id" | "name">;

✔ Reduces data exposure
✔ Common in APIs


5️⃣ Omit<T, K>

Remove specific properties from a type.

type UserWithoutEmail = Omit<User, "email">;

6️⃣ Record<K, T>

Creates an object type with fixed keys and same value type.

type Roles = "admin" | "user";

type RolePermissions = Record<Roles, string[]>;

const permissions: RolePermissions = {
admin: [“read”, “write”],
user: [“read”]
};


7️⃣ Exclude<T, U>

Remove types from a union.

type Status = "pending" | "approved" | "rejected";

type ActiveStatus = Exclude<Status, “rejected”>;


8️⃣ Extract<T, U>

Extract matching types from a union.

type Result = Extract<Status, "approved" | "pending">;

9️⃣ NonNullable<T>

Removes null and undefined.

type Name = string | null | undefined;

type SafeName = NonNullable<Name>;


🔟 ReturnType<T>

Gets a function’s return type.

function getUser() {
return { id: 1, name: "Sanjit" };
}
type UserReturn = ReturnType<typeof getUser>;


1️⃣1️⃣ Parameters<T>

Extracts parameter types as a tuple.

function login(id: number, token: string) {}

type LoginParams = Parameters<typeof login>;
// [number, string]


🔑 Utility Types Summary

Utility Purpose
Partial Optional properties
Required Force required
Readonly Immutable
Pick Select properties
Omit Remove properties
Record Key-value map
Exclude Remove union types
Extract Pick union types
NonNullable Remove null/undefined
ReturnType Function return
Parameters Function params

⭐ Best Practices

✔ Prefer utility types over rewriting interfaces
✔ Use Pick / Omit in APIs
✔ Use Partial for PATCH operations
✔ Combine utility types when needed

You may also like...