TypeScript Tutorial · Generics and Type Manipulation · Lesson 17 of 25
TypeScript Utility Types
Partial, Required, Readonly, Pick, Omit, Record, ReturnType and friends.
Built-in type transformations
TypeScript ships with generic utility types that derive new types from existing ones:
| Utility | Result |
|---|---|
Partial<T> |
all properties optional |
Required<T> |
all properties required |
Readonly<T> |
all properties readonly |
Pick<T, K> |
only properties K |
Omit<T, K> |
all properties except K |
Record<K, V> |
object with keys K and values V |
ReturnType<F> / Parameters<F> |
a function's return / parameter types |
Awaited<T> |
the value a promise resolves to |
NonNullable<T> |
removes null and undefined |
interface User {
id: number;
name: string;
email: string;
isAdmin: boolean;
}
type UserUpdate = Partial<Omit<User, "id">>; // everything but id, all optional
type PublicUser = Pick<User, "id" | "name">;
type UsersById = Record<number, PublicUser>;
function updateUser(user: User, changes: UserUpdate): User {
return { ...user, ...changes };
}
const ada: User = { id: 1, name: "Ada", email: "[email protected]", isAdmin: false };
const promoted = updateUser(ada, { isAdmin: true });
const directory: UsersById = { [ada.id]: { id: ada.id, name: ada.name } };
function makeUser() { return { id: 2, name: "Lin" }; }
type Made = ReturnType<typeof makeUser>; // { id: number; name: string }
const lin: Made = makeUser();
console.log(promoted.isAdmin, directory[1], lin);
Output
true { id: 1, name: 'Ada' } { id: 2, name: 'Lin' }Implement Pick and Omit yourself in the Pick & Omit problem.
Test yourself
Which utility type makes every property optional?
Optional<T>Partial<T>Maybe<T>Pick<T>
Show answer
Answer: Partial<T>
Practice next
- Typed pick() and omit() · coding problem