0
0
Typescriptprogramming~7 mins

Generic conditional constraints in Typescript

Choose your learning style9 modes available
Introduction

Generic conditional constraints let you control what types a generic can accept based on conditions. This helps make your code safer and clearer.

When you want a generic type to accept only certain types based on a condition.
When you want to create flexible functions or classes that behave differently for different types.
When you want to prevent wrong types from being used with generics.
When you want to write reusable code that adapts to input types.
When you want to enforce rules on generic types without writing many overloads.
Syntax
Typescript
function example<T extends U ? X : Y>(param: T): void {
  // function body
}

The extends keyword is used to set a constraint on the generic type T.

You can use a conditional type inside the constraint to decide which type T can be.

Examples
This example limits T to be either string or number.
Typescript
function process<T extends string | number>(value: T) {
  console.log(value);
}
This uses a conditional type to decide the type of result based on T.
Typescript
type ConditionalType<T> = T extends string ? number : boolean;

function example<T>(value: T, result: ConditionalType<T>) {
  console.log(result);
}
This example shows a generic constrained to either number or string.
Typescript
function checkType<T extends number | string>(value: T) {
  // T can be number or string
  console.log(value);
}
Sample Program

This program uses a conditional type ResultType to decide the type of result based on whether input is a string or not. It prints different messages accordingly.

Typescript
type ResultType<T> = T extends string ? number : boolean;

function processValue<T>(input: T, result: ResultType<T>) {
  if (typeof input === 'string') {
    console.log(`Input is string: ${input}, result is number: ${result}`);
  } else {
    console.log(`Input is not string: ${input}, result is boolean: ${result}`);
  }
}

processValue('hello', 5);
processValue(10, true);
OutputSuccess
Important Notes

Conditional constraints help catch errors early by limiting generic types.

They make your code more flexible and reusable.

Remember that conditional types run at compile time, so they don't affect runtime performance.

Summary

Generic conditional constraints let you control generic types based on conditions.

They improve code safety and flexibility.

Use them to create smarter, reusable functions and types.