DeployU
Interviews / Frontend Engineering / What are conditional types and how do you use them in TypeScript?

What are conditional types and how do you use them in TypeScript?

conceptual Advanced Types Interactive Quiz Code Examples

The Scenario

You are a frontend engineer at a social media company. You are writing a new function that needs to have a different return type depending on the type of its input.

You could write a separate function for each input type, but this would be repetitive and would violate the DRY (Don’t Repeat Yourself) principle.

The Challenge

Explain what conditional types are in TypeScript and how you would use them to solve this problem. What are the key benefits of using conditional types?

Wrong Approach

A junior engineer might not be aware of conditional types. They might try to solve this problem by using a series of `if` statements, which would not be a very elegant or type-safe solution.

Right Approach

A senior engineer would know that conditional types are the perfect tool for this job. They would be able to explain what conditional types are and how to use them to create a function with a dynamic return type.

Step 1: Understand What Conditional Types Are

A conditional type is a type that is selected based on a condition. It has the following syntax:

T extends U ? X : Y

If T extends U, the type is X. Otherwise, the type is Y.

Step 2: Write a Simple Conditional Type

Here’s how we can write a simple conditional type to get the type of the elements of an array:

type ElementType<T> = T extends (infer U)[] ? U : T;

In this example, if T is an array type, the type is U (the type of the elements of the array). Otherwise, the type is T.

Step 3: Solve the Problem

Here’s how we can use a conditional type to create a function with a dynamic return type:

function myFunc<T>(arg: T): ElementType<T> {
  // ...
}

Now, the return type of myFunc will depend on the type of its input.

The infer Keyword

The infer keyword is used in conditional types to infer a type from another type. In the ElementType example above, we use infer U to infer the type of the elements of the array.

Practice Question

You want to create a new type that is the return type of a function. Which of the following would you use?