#typescript #types #advanced

Day 20: Utility Types

The Toolkit

Welcome to Day 20! TypeScript provides a set of built-in types to transform existing types. You will use these every day.

1. Partial<Type>

Makes all properties optional. Great for โ€œupdateโ€ functions.

interface Todo { title: string; desc: string; }

function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
  return { ...todo, ...fieldsToUpdate };
}

2. Required<Type>

The opposite of Partial. Makes everything required.

3. Readonly<Type>

Makes all properties readonly.

const todo: Readonly<Todo> = { title: "Read", desc: "Book" };
// todo.title = "Sleep"; // Error

4. Pick<Type, Keys>

Creates a new type by picking a set of properties.

type TodoPreview = Pick<Todo, "title">;
// { title: string }

5. Omit<Type, Keys>

The opposite of Pick. Removes keys.

type TodoDesc = Omit<Todo, "title">;
// { desc: string }

Challenge for Today

  1. Create an interface User with id, name, email.
  2. Create a type CreateUserDto using Omit to remove id.
  3. Create a type UpdateUserDto using Partial on CreateUserDto.

See you on Day 21 for Mapped Types!