Sub topic 1
Why TypeScript Utility Types Exist
Prerequisites
Assume you know TypeScript type annotations, interfaces, type aliases, union types, string literal types, and generic syntax such as Array<T>.
Deriving Types Instead of Repeating Them
A utility type is a built-in generic type that creates a new type from an existing one. Utility types help keep related types consistent. When the original type changes, derived types update automatically.
For example, an application might use one User type for stored users, new-user forms, and update requests. Writing each type separately repeats information and can allow them to drift apart.
Partial: Making Every Property Optional
Partial<T> makes every property in T optional. It is useful for patch or update data, where callers may send only the fields that changed.
interface User {
id: number;
name: string;
email: string;
}
type UserUpdate = Partial<User>;
const changes: UserUpdate = { email: "[email protected]" };changes may contain any subset of User properties, including an empty object. Partial is shallow: it changes properties directly on User, not properties inside nested objects.
Pick and Omit: Selecting and Removing Properties
Pick<T, K> creates a type containing only the selected keys. Omit<T, K> creates a type containing every property except the selected keys.
interface User {
id: number;
name: string;
email: string;
}
type UserPreview = Pick<User, "id" | "name">;
type NewUser = Omit<User, "id">;
const preview: UserPreview = { id: 1, name: "Ada" };
const newUser: NewUser = {
name: "Ada",
email: "[email protected]",
};These types communicate intent. A preview should not expose every field, and a new-user request should not allow a client to choose the database-generated id.
A common composition combines Partial and Omit:
type UserPatch = Partial<Omit<User, "id">>;
function updateUser(id: number, patch: UserPatch): void {
console.log(id, patch);
}
updateUser(1, { name: "Grace" });Exercise
Which utility type creates a type with only id and name from User?
Show answer
Pick<User, "id" | "name">.