What Are Conditional Types in TypeScript?

Learn What Are Conditional Types in TypeScript? with practical examples, explanations, best practices, and real-world coding techniques.

Introduction to Conditional Types

Conditional types are an advanced TypeScript feature that allows a type to be selected based on a condition. They make it possible to describe relationships between types without manually defining a separate type for every possible situation.

In everyday development, different input types may require different output types. For example, a reusable utility might extract the element type from an array while leaving a non-array type unchanged. Conditional types let TypeScript express this behavior directly in the type system.

Conditional types are particularly useful when building generic functions, reusable libraries, API response models, type transformations, and utility types. They are evaluated by the TypeScript compiler and do not create runtime conditions in the generated JavaScript.

1. Understanding Conditional Type Syntax

A conditional type uses the extends keyword to check whether one type is assignable to another. Based on that condition, TypeScript selects one of two possible types.

type Result = T extends string ? "Yes" : "No";

type StringResult = Result;
// "Yes"

type NumberResult = Result;
// "No"

The general syntax is T extends U ? X : Y. Here, T is the type being checked, U is the comparison type, X is returned when the condition is satisfied, and Y is returned otherwise.

The condition is based on type assignability, not strict equality between two type names. A type can satisfy a condition when it is assignable to the comparison type, even when the two types have different names.

Unlike a JavaScript conditional expression, this syntax describes a compile-time type decision. It does not execute an if-else statement when your application runs.

2. Creating Conditional Types with Generics

Conditional types become especially powerful when combined with generics. Instead of checking one fixed type, you can create a reusable type that evaluates different conditions for different type arguments.

type IsArray = T extends unknown[]
  ? true
  : false;

type StringArray = IsArray;
// true

type NumberArray = IsArray;
// true

type StringValue = IsArray;
// false

The generic parameter T represents the type provided by the caller. The conditional type checks whether that type is assignable to unknown[] and selects the corresponding result.

You can also use conditional types to select between object structures:

type ApiResult = T extends string
  ? { message: T }
  : { data: T };

type MessageResult = ApiResult;
// { message: string }

type UserResult = ApiResult<{ id: number }>;
// { data: { id: number } }

This pattern is useful when a reusable type needs to represent different output structures depending on the type of its input.

3. Conditional Types and Type Assignability

The extends condition checks assignability. Understanding this distinction helps prevent mistakes when designing more advanced types.

type IsAssignableToNumber =
  T extends number ? true : false;

type A = IsAssignableToNumber<100>;
// true

type B = IsAssignableToNumber;
// true

type C = IsAssignableToNumber;
// false

type D = IsAssignableToNumber;
// never

The literal type 100 is assignable to number, so the condition succeeds. A string type is not assignable to number, so the alternative branch is selected.

Notice that never produces a different result from an ordinary failed condition. This happens because conditional types with a naked generic type parameter distribute over union members, and never represents an empty union. No members exist to evaluate, so the result is never.

4. Distributive Conditional Types

One of the most important features of conditional types is distribution over unions. When a conditional type operates directly on a naked generic type parameter, TypeScript evaluates the condition separately for each member of a union.

type ToArray = T extends unknown ? T[] : never;

type StringOrNumberArray = ToArray;

// string[] | number[]

Instead of evaluating string | number as one indivisible type, TypeScript evaluates the condition for string and number separately. The resulting types are then combined into a union.

Distribution makes many powerful transformations possible. For example, a reusable utility can filter out specific members of a union or transform each member independently.

type RemoveStrings =
  T extends string ? never : T;

type Values = RemoveStrings;
// number | boolean

The condition returns never for the string member. Because never contributes no members to a union, the remaining result is number | boolean.

A distributive conditional type must use a naked type parameter on the left side of extends. Wrapping that parameter in another type, such as a tuple, changes the distribution behavior.

5. Preventing Distribution with Tuple Wrapping

Sometimes you need to evaluate an entire union as a single type rather than process its members individually. You can prevent distributive behavior by wrapping the checked type in a tuple on both sides of the condition.

type ToArray = T extends unknown
  ? T[]
  : never;

type Distributed = ToArray;
// string[] | number[]

type ToArrayWhole = [T] extends [unknown]
  ? T[]
  : never;

type NotDistributed = ToArrayWhole;
// (string | number)[]

In the first type, T is checked directly, so a union is distributed. In the second type, the compiler checks [T] as a whole. The condition succeeds and the original union becomes the element type of one array.

This distinction matters when a utility must treat a collection of possible types as one combined value. The two results are different: string[] | number[] describes an array of strings or an array of numbers, while (string | number)[] allows strings and numbers in the same array.

6. Extracting Types with infer

TypeScript provides the infer keyword for introducing a type variable inside the condition of a conditional type. It allows you to capture a part of a type and reuse it in the selected branch.

One common example is extracting the element type of an array:

type ElementType =
  T extends (infer Item)[] ? Item : T;

type Names = ElementType;
// string

type Scores = ElementType;
// number

type Message = ElementType;
// string

When T matches an array structure, infer Item captures the element type. The true branch returns that inferred type. If the input is not an array, the false branch returns the original type.

You can use the same approach to extract a function's return type:

type MyReturnType =
  T extends (...args: never[]) => infer Result
    ? Result
    : never;

type UserFunction = () => {
  id: number;
  name: string;
};

type UserResult = MyReturnType;
// { id: number; name: string }

Here, infer Result captures the function's return type. TypeScript also provides the built-in ReturnType utility for this common requirement, but understanding infer helps when creating custom type transformations.

7. Using Conditional Types with Function Parameters

Conditional types can inspect function signatures and extract specific information. This is helpful when defining reusable abstractions around callbacks, handlers, and function-based APIs.

type FirstParameter =
  T extends (first: infer First, ...args: never[]) => unknown
    ? First
    : never;

type SaveUser = (
  userId: number,
  name: string
) => void;

type SaveUserId = FirstParameter;
// number

The conditional type checks whether the supplied type matches a function signature. The infer First variable captures the first parameter's type, which is then returned by the true branch.

In production code, prefer TypeScript's built-in utilities when they already express the intended operation. For example, Parameters<T> retrieves a tuple containing a function's parameter types, and indexed access can retrieve a particular parameter type from that tuple.

type SaveUserParameters = Parameters;

type SaveUserId = SaveUserParameters[0];
// number

type SaveUserName = SaveUserParameters[1];
// string

8. Conditional Types and the never Type

The never type represents a value that cannot exist. In conditional types, it is commonly used to remove unwanted union members or represent cases that should not be possible.

type ExcludeCustom =
  T extends U ? never : T;

type AllowedValues = ExcludeCustom<
  string | number | boolean,
  string
>;

// number | boolean

Because the condition distributes across union members, each member is checked independently. The string member matches the condition and becomes never; the number and boolean members remain in the final union.

This is the principle behind TypeScript's built-in Exclude<T, U> utility type. You can also use Extract<T, U> to keep members of one union that are assignable to another type.

type Values = string | number | boolean;

type NumericValues = Extract;
// number

type NonStringValues = Exclude;
// number | boolean

9. Useful Built-in Conditional Utility Types

TypeScript includes several utility types that use conditional type behavior. These utilities save time and provide well-established patterns for common type transformations.

Utility Purpose Example
Exclude<T, U> Removes union members assignable to U Exclude<"a" | "b", "a">
Extract<T, U> Keeps union members assignable to U Extract<string | number, number>
NonNullable<T> Removes null and undefined NonNullable<string | null>
ReturnType<T> Obtains a function's return type ReturnType<typeof getUser>
Parameters<T> Obtains a function's parameter tuple Parameters<typeof saveUser>
Awaited<T> Recursively unwraps promise-like types Awaited<Promise<string>>

These utilities are helpful when deriving types from existing unions, functions, and asynchronous operations. For example, Awaited<T> can represent the value obtained after awaiting a promise, without manually repeating the resolved value's type.

async function loadUser() {
  return {
    id: 101,
    name: "Abhinash"
  };
}

type LoadedUser = Awaited<
  ReturnType
>;

// { id: number; name: string }

The example combines two utilities. ReturnType extracts the function's return type, and Awaited unwraps the promise-like result to obtain the user object type.

10. Conditional Types with Object Structures

Conditional types can inspect object structures and select a type depending on whether a required property exists. The infer keyword is useful for extracting the property's value type after a matching structure has been established.

type MessageOf =
  T extends { message: infer Message }
    ? Message
    : never;

type Email = {
  message: string;
};

type Notification = {
  message: {
    title: string;
    body: string;
  };
};

type EmailMessage = MessageOf;
// string

type NotificationMessage = MessageOf;
// { title: string; body: string }

The condition checks whether the provided type has a compatible message property. If it does, infer Message captures the property's type.

If the supplied type does not satisfy the condition, the utility returns never. This makes the type reusable across different structures while still describing its output precisely.

11. Common Mistakes to Avoid

  • Confusing assignability with equality: the extends condition checks whether one type is assignable to another, not whether both type expressions are identical.
  • Forgetting distribution: a conditional type using a naked generic type parameter distributes over unions, which can produce a union of transformed results instead of one combined result.
  • Assuming never behaves like an ordinary type: a distributive conditional applied to never results in never because the union has no members to process.
  • Using infer outside a conditional pattern: infer introduces a type variable within the extends pattern of a conditional type.
  • Making every type transformation custom: built-in utilities such as Exclude, Extract, ReturnType, and Awaited already handle many common requirements.
  • Expecting runtime validation: conditional types are resolved by the compiler and cannot validate external JSON or change program behavior at runtime.

12. Best Practices for Conditional Types

  • Use conditional types when a type genuinely depends on another type, rather than adding unnecessary complexity to simple models.
  • Choose meaningful names for generic parameters and inferred types so complex transformations remain understandable.
  • Test conditional types against individual types, union types, never, and relevant edge cases.
  • Use tuple wrapping when the intended behavior requires testing an entire union without distribution.
  • Use infer to capture parts of a structure rather than manually duplicating complex type definitions.
  • Prefer TypeScript's built-in utility types whenever they already match the required transformation.
  • Keep runtime validation separate from compile-time type relationships when dealing with API responses or other untrusted data.

Conclusion

Conditional types allow TypeScript to select, filter, and transform types according to assignability conditions. The basic T extends U ? X : Y syntax provides the foundation for more advanced techniques, including distributing transformations over unions and extracting types with infer.

By combining conditional types with generics, indexed access types, and built-in utility types, you can build flexible abstractions that preserve type safety across different inputs. These concepts are particularly valuable when designing reusable libraries, strongly typed APIs, and large TypeScript applications.

Code Examples

Basic Conditional Type

typescript
type Result<T> = T extends string
  ? "Text"
  : "Other";

type A = Result<string>;
// "Text"

type B = Result<number>;
// "Other"

type C = Result<boolean>;
// "Other"
    

Distributive Conditional Types

typescript
type ToArray<T> =
  T extends unknown ? T[] : never;

type Result = ToArray<string | number>;
// string[] | number[]

type RemoveStrings<T> =
  T extends string ? never : T;

type Remaining = RemoveStrings<
  string | number | boolean
>;
// number | boolean
    

Prevent Distribution

typescript
type Distributed<T> =
  T extends unknown ? T[] : never;

type WholeArray<T> =
  [T] extends [unknown] ? T[] : never;

type A = Distributed<string | number>;
// string[] | number[]

type B = WholeArray<string | number>;
// (string | number)[]
    

Extract an Array Element Type

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

type Names = ElementType<string[]>;
// string

type Scores = ElementType<number[]>;
// number

type Value = ElementType<boolean>;
// boolean
    

Combine ReturnType and Awaited

typescript
async function loadUser() {
  return {
    id: 101,
    name: "Abhinash"
  };
}

type UserPromise = ReturnType<typeof loadUser>;
type User = Awaited<UserPromise>;

// User is:
// { id: number; name: string }

const user: User = {
  id: 102,
  name: "Ravi"
};
    

Pro Tip

When a conditional type produces unexpected results for a union, check whether the condition is distributive. Use `T extends U ? X : Y` to process union members individually, or `[T] extends [U] ? X : Y` to evaluate the union as a whole. This distinction is essential when writing advanced TypeScript utilities.

More TypeScript lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.