×

typescript · level 3 · unit 3 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

and cut a type down to what you need.

A user record might hold a name, an email and a password. A public profile should never carry the password. Pick<User, "name" | "email"> keeps only the keys you list. Omit<User, "password"> keeps everything except the keys you list.

Both stay linked to User. Rename a field or add a new one and every smaller type updates itself. Give a smaller type an extra property in an object literal and the checker reports TS2353.

interface User {
  id: number;
  name: string;
  email: string;
  password: string;
}
type Contact = Pick<User, "name" | "email">;
type PublicUser = Omit<User, "password">;
function toPublic(user: User): PublicUser {
  return { id: user.id, name: user.name, email: user.email };
}
const contact: Contact = { name: "Ada", email: "ada@example.com" };
const ada = toPublic({ id: 1, ...contact, password: "hunter2" });
console.log(ada, contact.name);

Pick checks that every key you list exists. Omit does not, so spell its keys carefully.