Partial, Required, Readonly, Pick, Omit, and Record - Textnotes

Partial, Required, Readonly, Pick, Omit, and Record


Learn how to use TypeScript utility types to transform existing types. This module explains Partial, Required, Readonly, Pick, Omit, and Record with practical examples for real-world applications.

1. Partial

The Partial utility type makes all properties of a type optional. It is commonly used for update operations.

Example


interface User {
id: number;
name: string;
email: string;
}

function updateUser(user: User, updates: Partial<User>) {
return { ...user, ...updates };
}

const updatedUser = updateUser({ id: 1, name: "Muni", email: "muni@example.com" }, { name: "Ravi" });

2. Required

The Required utility type makes all properties of a type mandatory.

Example


interface Config {
apiUrl?: string;
timeout?: number;
}

const fullConfig: Required<Config> = {
apiUrl: "https://api.example.com",
timeout: 5000
};

3. Readonly

The Readonly utility type makes all properties of a type immutable.

Example


interface Product {
id: number;
name: string;
}

const product: Readonly<Product> = { id: 101, name: "Laptop" };
// product.name = "Desktop"; // Error

Readonly ensures data cannot be modified after initialization.

4. Pick

The Pick utility type allows selecting specific properties from an existing type.

Example


interface User {
id: number;
name: string;
email: string;
}

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

const preview: UserPreview = { id: 1, name: "Muni" };

Pick is useful for creating lighter versions of types for specific use cases like API responses.

5. Omit

The Omit utility type excludes specific properties from a type.

Example


interface User {
id: number;
name: string;
email: string;
}

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

const user: UserWithoutEmail = { id: 1, name: "Muni" };

Omit is useful when certain properties should not be exposed in a context, such as public APIs.

6. Record

The Record utility type constructs an object type with specified keys and values.

Example


type Roles = "admin" | "user" | "guest";
type Permissions = Record<Roles, string[]>;

const rolePermissions: Permissions = {
admin: ["read", "write", "delete"],
user: ["read", "write"],
guest: ["read"]
};

Record is widely used to create maps or dictionaries with fixed keys and consistent value types.

Conclusion

Utility types in TypeScript like Partial, Required, Readonly, Pick, Omit, and Record help transform and reuse existing types effectively. They improve code maintainability, enforce type safety, and simplify real-world application development.