typescript · level 3 · unit 3 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Make a film card. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
interface Film {
title: string;
year: number;
rating: number;
}
type Card = Omit<Film, "rating">;
const card: Card = { title: "Up", year: 2009, rating: 5 };
console.log(card.title);
your turn
Your turn. Print a price label.
Choose the utility type that keeps only name and price, then fill in a product and its price.
fix it
The bank statement wants a PIN. Fix it.
- The checker says
pinis missing from the statement. But a statement should never show the PIN! Omitdoes not check its keys, so a misspelt key removes nothing at all.- Spell the key correctly on line 6:
Omit<Account, "pin">.
nailed it
your types share only what they should. :D
Pick<T, K>keeps only the keys you list.Omit<T, K>keeps every key except the ones you list.Omitnever checks its keys, so spell them carefully.
new words in your collection
- Pick
- Omit
This lesson isn’t saved. A free account remembers every lesson you finish.