Utility Types
TypeScript provides several massively powerful globally scoped global mapping Utility Types! These utilities magically manipulate existing Types cleanly into brand new structural configurations natively!
1. Partial<T>
Maps all required properties inside a given Type completely as Optional (?). Incredibly useful for backend PATCH (Update) endpoints dynamically!
interface Todo {
title: string;
description: string;
}
// To update a Todo, we might only send the description.
function updateTodo(id: number, fieldsToUpdate: Partial<Todo>) {
// fieldsToUpdate legally accepts { title?: string, description?: string }
}
updateTodo(1, { description: "Clean kitchen" }); // Perfectly valid!
2. Omit<T, Keys>
Strategically constructs a brand new Type natively by picking an old interface and banning specific keys cleanly.
interface UserProfile {
id: string;
username: string;
passwordHash: string;
}
// We ban passwordHash securely from the frontend return object natively!
type SafeFrontendUser = Omit<UserProfile, "passwordHash">;
const publicUser: SafeFrontendUser = {
id: "1",
username: "Alice"
};
3. Pick<T, Keys>
The exact opposite inverse logic of Omit. It constructs a new Type natively strictly grabbing ONLY the explicitly allowed keys requested natively.
type UsernameOnly = Pick<UserProfile, "username">;
4. Record<Keys, Type>
Builds a mapping dictionary dynamically bridging a strict key classification natively against a strict value classification natively.
// Dictionary mapping a String Key against a Number Value mapped natively
const scoreBoard: Record<string, number> = {
"Alice": 50,
"Bob": 100
};