How to use Conditional Types with Union Types In Javascript

In this approach, we leverage union types along with conditional types to define interfaces that adapt based on different types.

Syntax:

type ConditionalInterface<T> = T extends ConditionType1 ? InterfaceType1 :
T extends ConditionType2 ? InterfaceType2 :
DefaultInterfaceType;

Example: The following code demonstrates the usage of conditional types with union types to define interfaces dynamically.

JavaScript
type Fruit = 'apple' | 'banana';

type FruitProperties<T> = T extends 'apple' ? { color: string } :
                          T extends 'banana' ? { length: number } :
                          never;

const appleProperties: FruitProperties<'apple'> = { color: 'red' };
const bananaProperties: FruitProperties<'banana'> = { length: 10 };

console.log(appleProperties); // Output: { color: 'red' }
console.log(bananaProperties); // Output: { length: 10 }

Output

{ color: 'red' }
{ length: 10 }


How to Create an Interface with Condtional Type ?

Conditional types in TypeScript offer developers the ability to craft interfaces that adapt their behavior based on the types they encounter. This feature enhances code flexibility and adaptability, particularly in situations where types may vary.

By employing conditional types, developers can define interfaces that dynamically adjust their structure and constraints, providing powerful tools for building robust and type-safe applications.

Table of Content

  • Using extends keyword with interfaces
  • Using extends keyword with Mapped Types
  • Using Conditional Types with Union Types:

Similar Reads

Using extends keyword with interfaces

This approach involves using conditional types to discriminate between different types and define interface properties accordingly to conditionally extend the interface....

Using extends keyword with Mapped Types

Mapped types with conditional constraints transform existing types into new interfaces based on certain conditions....

Using Conditional Types with Union Types:

In this approach, we leverage union types along with conditional types to define interfaces that adapt based on different types....