Questions
What are utility types and how do you use them in TypeScript?
The Scenario
You are a frontend engineer at a social media company. You are writing a new function that needs to take a subset of the properties of an existing type.
You could create a new type with only the properties that you need, but this would be repetitive and would violate the DRY (Don’t Repeat Yourself) principle.
The Challenge
Explain what utility types are in TypeScript and how you would use them to solve this problem. What are the key benefits of using utility types?
A junior engineer might not be aware of utility types. They might try to solve this problem by creating a new type with only the properties that they need, which would be a verbose and difficult to maintain solution.
A senior engineer would know that utility types are the perfect tool for this job. They would be able to explain what utility types are and how to use them to create new types from existing types.
Step 1: Understand What Utility Types Are
Utility types are a set of built-in types in TypeScript that allow you to create new types from existing types.
Step 2: The Key Utility Types
| Type | Description |
|---|---|
Partial<T> | Creates a new type with all the properties of T set to optional. |
Readonly<T> | Creates a new type with all the properties of T set to readonly. |
Pick<T, K> | Creates a new type by picking a set of properties K from T. |
Omit<T, K> | Creates a new type by omitting a set of properties K from T. |
Record<K, T> | Creates a new type with a set of properties K of type T. |
Step 3: Solve the Problem
For our use case, we can use the Pick utility type to create a new type with only the properties that we need.
interface User {
id: number;
name: string;
email: string;
}
type UserSummary = Pick<User, "id" | "name">;
const userSummary: UserSummary = {
id: 1,
name: "John Smith"
}; Practice Question
You want to create a new type that has all the properties of an existing type, but with all the properties set to optional. Which of the following would you use?