Course contentsShow
← TypeScript
Lesson 646 of 1,79615. Generic ConstraintsFree lesson

Conditional Constraints for Function Signatures

Applying conditional constraints to function type parameters to accept different shapes based on input types.

Conditional Constraints for Function Signatures

What you'll learn: How to apply conditional type logic within extends constraints to make your function accept different argument shapes based on the input types.


The Core Idea

Sometimes a function should accept completely different parameters depending on what type you pass in. For example, you might want a function that:

  • Accepts a simple value when the input is a primitive
  • Requires an object with specific properties when the input is an array

Conditional constraints let you write extends clauses that check a condition and enforce different constraints based on the result.

How It Works

You combine what you know about conditional types with generic constraints:

function process<T extends string extends T ? never : { length: number }>(
  value: T
): void {
  // Only arrays/strings allowed, not plain strings
}

A more practical pattern:

function wrap<T>(
  value: T,
  options: T extends Array<any> ? { multi: true } : { single: true }
): void {
  // If T is an array, options must be { multi: true }
  // Otherwise, options must be { single: true }
}

wrap([1, 2], { multi: true });  // ✓
wrap(42, { single: true });      // ✓
wrap([1, 2], { single: true });  // ✗ Error!

The Pattern

The syntax follows: param: T extends Condition ? TypeIfTrue : TypeIfFalse

This forces the function signature to adapt based on what T turns out to be at the call site.

When This Matters

Use conditional constraints when you're building utility functions that genuinely need different "shapes" of arguments for different input types—like serializers, validators, or configuration builders where the options object changes based on the data type.

Key Takeaway: Conditional constraints in function signatures let you enforce that certain parameters have different required shapes depending on the generic type argument, making your functions both flexible and type-safe.