Utility types
TypeScript ships utility types that build new types from existing ones, so you do not repeat yourself:
interface User {
id: number;
name: string;
email: string;
password: string;
}
| Utility | Gives |
|---|---|
Partial<User> |
every property optional (good for "changes") |
Required<T> |
every property required |
Readonly<User> |
every property read-only |
Pick<User, "id" | "name"> |
only those properties |
Omit<User, "password"> |
everything except those |
Record<"admin" | "guest", boolean> |
an object with exactly those keys |
type UserSummary = Pick<User, "id" | "name">; // { id: number; name: string }
type Settings = Record<"darkMode" | "emails", boolean>;
Because these are derived, adding a field to User updates every type built from it automatically.
Types are not runtime checks
Omit<User, "password"> only changes what TypeScript allows you to write. The object still contains whatever you put in it. To really remove the password, the code must leave it out, for example with destructuring:
const { password, ...safe } = user; // safe has everything except password
Your task
updateUser(user: User, changes: Partial<User>): Userreturns a new user with the changes applied.- Define
type PublicUser = Omit<User, "password">. toPublic(user: User): PublicUserreturns a copy without the password.