TypeScript Intermediate: Generics and Utility Types
Utility Types
In this lesson you will
- Use Partial, Required, Readonly, Pick and Omit
- Build lookup objects with Record
- Extract types from functions with ReturnType and Parameters
Introduction
Imagine you have a User type, and now you need a version for an update form where every field is optional, and another that leaves out the password. Copying and editing the type creates duplicates that drift apart. TypeScript ships with utility types: generic helpers that build new types from existing ones. They are built on generics, which you just learned.
All examples use this type:
Partial and Required
Partial<T> makes every property optional. Perfect for "update" operations, where only some fields change.
Required<T> does the opposite: it makes every property required.
Readonly
Readonly<T> makes all properties read-only, which is a good way to protect data you pass around.
Quick quiz
Which utility type makes every property of a type optional?
Pick and Omit
Pick<T, Keys> keeps only the listed properties. Omit<T, Keys> removes them.
Because they derive from User, if you add a field to User later, PublicUser picks it up automatically.
Record
Record<Keys, Type> builds an object type with the given keys, all holding the same type of value. Great for lookup tables.
Remove one of the roles from the object and TypeScript reports the missing key. This makes Record with a union of keys a handy way to be sure you handled every case.
Getting types out of functions
Instead of writing a type that duplicates a function, extract it.
typeof makeUser takes the type of the function value, ReturnType extracts what it returns, and Parameters gives the arguments as a tuple.
A few more
NonNullable<T>removesnullandundefined.Exclude<Union, Members>removes members from a union.Extractkeeps them.Awaited<T>gives the value inside a promise.
Quick quiz
What does Omit<User, 'password'> give you?
Try it yourself
Using Product below, create a type ProductPreview containing only name and price, and a type ProductDraft where everything except id is optional. Hint: combine Pick, Partial and Omit.
Summary
- Utility types derive new types from existing ones, so you never copy and edit.
Partial,RequiredandReadonlychange every property at once.Pickkeeps chosen properties,Omitremoves them, andRecordbuilds lookup types.ReturnTypeandParametersextract types from functions withtypeof.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading