Developers frequently claim that typescript requires them to write redundant code. The reasons can vary, but one of the most common is a failure to use utility types.
They are provided in typescript to make our lives easier. Let's take a look at them one at a time.
Partial<T> allows you to create optional props with a single line of code. Without it, we'd need to duplicate the User type, which isn't ideal.
Below is an example of
Partial utility type.
Partial takes type as an argument.
Required<T> is the inverse of Partial. It creates all the necessary props.
Required also takes type as an argument.
readonly functions similarly to const. You cannot reassign a type once it has been marked as
NonNullable<T> filters your type and removes null and undefined from the union of types.
Exclude<T, K> lets you remove type from the union types.
It takes two arguments. The first is type, while the second is a union of props.
Extract<T, K> is the inverse of
Exclude. It will generate union types based on the specified union type.
Pick<T, K> picks props from type. It will give you a new type.
Omit<T, K> removes props from types.
ReturnType<T> gives return type of function.
Record<T, K>creates an object type.
Instead of doing this:
You can do this:
Record also accepts union type as key that is not supported by interface and type.
As we can see, utility types help in avoiding redundancy in the codebase. It also enables maintaining a single source of truth.
That's it for today. I hope you enjoyed this blog. Stay tuned for upcoming blogs on the typescript.