Skip to main content
eLearner.app
Module 6 · Lesson 1 of 211/14 in the course~15 min
Module lessons (1/2)

Conditional Types and infer

Conditional types allow you to express non-trivial type decisions based on inheritance relationships. The syntax resembles JavaScript's ternary operator:

TS
T extends U ? X : Y

If type T is assignable to U, then the resulting type will be X, otherwise it will be Y.


Basic Conditional Types

A conditional type evaluates a condition at compile time:

TS
type IsNumber<T> = T extends number ? true : false;

type A = IsNumber<number>; // true
type B = IsNumber<string>; // false

This pattern is extremely powerful when combined with generics to create flexible and dynamic utility types.


Type Extraction with infer

Inside the extends clause of a conditional type, we can use the infer keyword to declare a type variable to be inferred by the compiler.

For example, if we want to extract the return type of a function:

TS
type GetReturnType<T> = T extends (...args: any[]) => infer R ? R : never;

type ExampleFunction = () => string;
type Return = GetReturnType<ExampleFunction>; // string

In this example, infer R tells TypeScript to automatically determine the function's return type and make it available as R in the positive branch of the conditional.


Try it yourself

Exercise 1: The IsString Type

Exercise#ts.m6.l1.e1
Attempts: 0Loading…

Create a generic type named IsString<T> that returns the literal type true if T extends string, otherwise false.

Loading editor…
Show hint

Use the syntax type IsString<T> = T extends string ? true : false; to check the type.

Solution available after 3 attempts

Exercise 2: Extracting a type from an Array with infer

Exercise#ts.m6.l1.e2
Attempts: 0Loading…

Define a generic type UnpackArray<T> that uses infer to extract the element type of an array T. If T is an array (for example U[]), return U, otherwise return the same type T.

Loading editor…
Show hint

Use T extends (infer U)[] ? U : T to declare and return the inferred type variable U.

Solution available after 3 attempts