TS Utility Types
TypeScript provides a set of built-in utility types that help manipulate existing types to create new ones. These types make it easier to work with complex type transformations.
Key Topics
Partial
The Partial
utility type makes all properties of a type optional.
interface User {
id: number;
name: string;
email: string;
}
let partialUser: Partial = { name: "Alice" };
console.log(partialUser); // { name: "Alice" }
Output
{ name: "Alice" }
Explanation: The Partial
utility type allows the creation of an object with some properties of the User
interface while leaving others undefined.
Readonly
The Readonly
utility type makes all properties of a type immutable.
interface User {
id: number;
name: string;
}
const readonlyUser: Readonly = { id: 1, name: "Alice" };
// readonlyUser.id = 2; // Error: Cannot assign to 'id' because it is a read-only property.
console.log(readonlyUser);
Output
{ id: 1, name: "Alice" }
Explanation: The Readonly
utility type ensures that the properties of readonlyUser
cannot be modified after initialization.
Pick
The Pick
utility type allows you to create a new type by selecting specific properties from an existing type.
interface User {
id: number;
name: string;
email: string;
}
type UserPreview = Pick;
const userPreview: UserPreview = { name: "Alice", email: "alice@example.com" };
console.log(userPreview);
Output
{ name: "Alice", email: "alice@example.com" }
Explanation: The Pick
utility type creates a new type UserPreview
with only the name
and email
properties from the User
interface.
Omit
The Omit
utility type creates a new type by excluding specific properties from an existing type.
interface User {
id: number;
name: string;
email: string;
}
type UserWithoutEmail = Omit;
const userWithoutEmail: UserWithoutEmail = { id: 1, name: "Alice" };
console.log(userWithoutEmail);
Output
{ id: 1, name: "Alice" }
Explanation: The Omit
utility type creates a new type UserWithoutEmail
by excluding the email
property from the User
interface.
Record
The Record
utility type constructs a type with a set of keys and values of a specific type.
type Role = "admin" | "user" | "guest";
const roles: Record = {
admin: "Alice",
user: "Bob",
guest: "Charlie",
};
console.log(roles);
Output
{ admin: "Alice", user: "Bob", guest: "Charlie" }
Explanation: The Record
utility type creates a type where keys are Role
and values are string
.
Key Takeaways
- Partial: Makes all properties optional.
- Readonly: Prevents modification of properties after initialization.
- Pick: Creates a type by selecting specific properties.
- Omit: Creates a type by excluding specific properties.
- Record: Constructs a type with predefined keys and values.