#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
- Create an interface
Userwithid,name,email. - Create a type
CreateUserDtousingOmitto removeid. - Create a type
UpdateUserDtousingPartialonCreateUserDto.
See you on Day 21 for Mapped Types!