TypeScript: Utility Types
Table of Contents
Utility Types
📘 typescriptlang.org > utility-types
TypeScript provides a set of utility types that can be used to manipulate and transform existing types. These utility types are generic and can be applied to any type to create new types based on the original.
Partial<T>
📘 typescriptlang.org > Partial
- Description: Constructs a type with all properties of T set to optional.
- Usage: When you want to make some or all properties of a type optional.
interface User {
name: string;
age: number;
email: string;
}
function createUser(user: Partial<User>): User {
return {
name: "John Doe",
age: 30,
email: "john.doe@example.com",
...user,
};
}
const newUser = createUser({ name: "Jane Doe" });
console.log(newUser);
// Output: { name: 'Jane Doe', age: 30, email: 'john.doe@example.com' }
Pick<T, K>
- Description: Constructs a type by picking a set of properties K from T.
- Usage: When you need to select specific properties from a type.
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick<Todo, "title" | "completed">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
Omit<T, K>
- Description: Constructs a type by omitting a set of properties K from T.
- Usage: When you want to exclude specific properties from a type.
interface Todo {
title: string;
description: string;
completed: boolean;
createdAt: number;
}
type TodoPreview = Omit<Todo, "description">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
createdAt: 1615544252770,
};
type TodoInfo = Omit<Todo, "completed" | "createdAt">;
const todoInfo: TodoInfo = {
title: "Pick up kids",
description: "Kindergarten closes at 5pm",
};
Readonly<T>
📘 typescriptlang.org > Readonly
- Description: Constructs a type with all properties of T set to readonly.
- Usage: When you want to make all properties of a type read-only.
interface Todo {
title: string;
}
const todo: Readonly<Todo> = {
title: "Delete inactive users",
};
todo.title = "Hello";
//ERROR: Cannot assign to 'title' because it is a read-only property.