There's a User with id, name and email. The sign-up form needs a version without id, the profile card only needs name and email, and update data (data that changes a user) may hold just some of the fields. Writing three new interfaces that are almost the same is tiring. And as soon as User changes, all three are out of date.
A utility type makes those versions directly from User. It's a built-in TypeScript type that makes a new type from a type you already have: Partial<User>, Pick<User, ...> or Omit<User, ...>. Think of photocopying: from one original document you can make a copy where every field may stay empty, a copy with only two fields, or a copy without a certain field. The original doesn't change. Here the original document is User, each field is one property, and each copy is a new type made by a utility type.
Every example below uses this interface:
interface User {
id: number;
name: string;
email: string;
age?: number; // optional
}
A utility type is written with angle brackets < >, just like a generic, because it is a generic: User fills its type parameter.
Partial and Required
Partial<T> makes every property optional. Required<T> is the opposite: every property becomes required, including the ones that had a ?. Here is Partial<User> next to a plain User:
// Partial<User> is the same as { id?: number; name?: string; email?: string; age?: number }
const empty: Partial<User> = {}; // passes
const wrong: User = {}; // error
error TS2739: Type '{}' is missing the following properties from type 'User': id, name, email
{} passes as a Partial<User>, but is refused as a User, because id, name and email are required. Partial fits update data that only changes some fields, like { email: "[email protected]" }.
Required<User> makes age required too, so an object without age is refused:
// Required<User> is the same as { id: number; name: string; email: string; age: number }
const complete: Required<User> = { id: 1, name: "Budi", email: "[email protected]" }; // error
error TS2741: Property 'age' is missing in type '{ id: number; name: string; email: string; }' but required in type 'Required<User>'.
Pick and Omit
Pick<T, K> keeps only certain properties. Omit<T, K> is the opposite: it drops certain properties and keeps the rest. K is a union of property names, like what keyof gives you.
type ProfileCard = Pick<User, "name" | "email">;
// the same as { name: string; email: string }
type SignUpForm = Omit<User, "id">;
// the same as { name: string; email: string; age?: number }
const form: SignUpForm = { id: 1, name: "Budi", email: "[email protected]" }; // error
The last line is rejected:
error TS2353: Object literal may only specify known properties, and 'id' does not exist in type 'Omit<User, "id">'.
Omitalready droppedid, so writing it counts as an unknown property.agestays optional in the result ofOmit, and also in the result ofPickwhenageis one of the names. These two utility types don't change the?.- An error message can list the keys (the property names) in another order than your code:
Pick<User, "name" | "email">can appear asPick<User, "email" | "name">.
Readonly and Record
Readonly<T> makes every property unchangeable once the object is made:
const admin: Readonly<User> = { id: 1, name: "Budi", email: "[email protected]" };
admin.name = "Ani"; // error
error TS2540: Cannot assign to 'name' because it is a read-only property.
Record<K, V> is the type of an object whose keys are of type K and whose values are of type V:
type Name = "budi" | "ani" | "rina";
const scores: Record<Name, number> = { budi: 7, ani: 7, rina: 7 }; // all three names required
const points: Record<string, number> = {}; // any string key, number values
points["budi"] = 0;
points["ani"] = 0; // points is now { budi: 0, ani: 0 }
- When
Kis a union likeName, every key is required. If you leave outrina, you get:Property 'rina' is missing in type '{ budi: number; ani: number; }' but required in type 'Record<Name, number>'. - When
Kisstring, the object may start empty, and keys can be added one at a time. In the exercise, you build one from an array of names and one numbervalue: start with an empty object, then setobj[name] = valueinside afor...of.
There are other utility types you will often meet. Say there is function makeUser(name: string): User and async function getUser(id: number): Promise<User>:
| Utility type | What it gives |
|---|---|
ReturnType<typeof makeUser> |
the function's return type: User |
Parameters<typeof makeUser> |
a tuple of its parameters: [name: string] |
Awaited<ReturnType<typeof getUser>> |
what the Promise holds (what you get with await): User |
NonNullable<string | null | undefined> |
string, without null and undefined |
Exclude<"small" | "medium" | "large", "small"> |
removes union members: "medium" | "large". Its opposite, Extract, keeps only the ones that match. |
typeof makeUser, written where a type goes, takes the type from a function that already exists. So the type changes when the function changes.
⚠️ A Partial that's too loose, and an Omit that stays quiet
- Partial for data that must be complete.
Partial<User>accepts{}, so incomplete data is accepted too. Use Partial only for data that may really be partial. - A typo in a key name in Omit.
Pick<User, "address">is refused (Type '"address"' does not satisfy the constraint 'keyof User'.), butOmit<User, "idd">says nothing and drops nothing. - Thinking Readonly holds while the program runs.
readonlyis only checked by TypeScript. After compiling, JavaScript can still change the property. - Forgetting to return the filled object. In the exercise, filling a
Recordinside a loop is no use if the function doesn'treturnthat object at the end.
TL;DR: Utility types are built-in types that make new types from existing ones. The examples use the interface User (id, name, email required, age optional). Partial<User> makes every property optional (so {} passes), Required<User> makes them all required, and Readonly<User> makes them unchangeable. Pick<User, "name" | "email"> keeps only the properties you name. Omit<User, "id"> is the opposite: it drops the properties you name. Record<K, V> is an object with keys (property names) of type K and values of type V, like Record<string, number> for a score per name such as { budi: 0, ani: 0 }.
⚡ Partial: everything becomes optional
Write:
const empty: Partial<User> = {}; // passes
const wrong: User = {}; // error
Meaning: User here is an interface with the required id, name and email, and the optional age?. A utility type such as Partial is a built-in type that makes a new type from User without changing the original. Partial<User> makes every property optional, so {} is accepted. This suits update data (data that changes only some of a user's fields). Required<User> is the opposite: everything is required, age? included.
⚡ Pick takes, Omit drops
Write:
type ProfileCard = Pick<User, "name" | "email">;
type SignUpForm = Omit<User, "id">;
Guess first: Omit drops the properties you name. Is Omit<User, "idd">, with a typo, rejected by TypeScript?
No. TypeScript says nothing, and Omit drops nothing. Pick with a wrong property name is rejected, Omit isn't.
Meaning: Pick keeps only the properties you name. Omit drops the ones you name and keeps the rest. The ? (optional) on age stays in the result of Omit.
⚡ Record: keys and values
Write:
const points: Record<string, number> = {};
points["budi"] = 0;
points["ani"] = 0; // { budi: 0, ani: 0 }
Meaning: Record<K, V> is an object with keys (property names) of type K and values of type V. When K is string, the object can start empty and be filled one key at a time. In the exercise, this object is made inside a function, so don't forget to return the object at the end of the function.