In this post, I will cover five TypeScript utility types practical in React applications.
What are Utility types?
When working with TypeScript, you’ll often need to construct new types on top of the existing ones. Creating new types this way has several advantages:
- Adhering to the DRY principle. Reusing the types you already have to build new ones means less redundancy and repetition in your code.
- Keeping your types in sync on changes. When you need to change the properties of some underlying type, the types that derive from it will also adopt the change.
As you might know, TypeScript has union and intersection types that people often use to construct new types. But TypeScript also ships a number of powerful utility types that are a better choice for handling more nuanced edge cases.
Utility types for React
keyof is an operator, not a utility type, but it’s used in a similar fashion.
keyof creates a union type consisting of the property names of the type you pass.
keyof is perfect for enforcing using the existing keys of the object:
When you assign
PostKeysType to a variable, that variable can only have a value of
Partial will return a new type with all of the props set to optional. It’s great for passing around a dynamic set of props where you don’t know in advance all the props you might receive:
We’re setting the
fieldsToUpdate type to
Partial<Post>. That allows passing an object with dynamic fields, as long as they are part of the
You can use
Pick to create a new type by specifying which properties you would like to copy. To pick the properties, you pass a union type:
The advantage of creating types this way is that you keep your types in sync. Changes to the properties of the parent type are automatically adopted by the derived one.
Omit as the opposite of
Pick. Rather than picking the set of props that you want to copy, you provide a set of properties you want to omit from the type.
Omit will copy all the props, except for the ones you passed:
Exclude works similarly to
Omit with one big difference - it works with union types. When you apply
Exclude to a union type, it removes a constituent of that union.
In this post, we covered the TypeScript utility types you are most likely to use when working on React projects. However, we’ve only scratched the surface with the utility types. There are many more utility types that TypeScript provides, and you can take a look at the exhaustive list here .
If you’d like to get more web development, React and TypeScript tips consider
following me on Twitter,
where I share things as I learn them.