Open In App

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.



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.



Syntax:

interface InterfaceName<T> {
propertyName:
T extends ConditionType ? TypeIfTrue : TypeIfFalse;
}

Example: The below code creates an interface with conditional type using extends keyword and ternary operator.




interface Vehicle<T> {
    type: T extends 'car' ?
    'four-wheeler' : 'two-wheeler';
    wheels: T extends 'car' ? 4 : 2;
}
 
const car: Vehicle<'car'> = {
    type: 'four-wheeler',
    wheels: 4
};
 
const bike: Vehicle<'bike'> = {
    type: 'two-wheeler',
    wheels: 2
};
 
console.log(car);
console.log(bike);

Output:

{ type: four-wheeler, wheels: 4 } 
{ type: two-wheeler, wheels: 2 }

Using extends keyword with Mapped Types

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

Syntax:

type MappedTypeName<T> = {
[P in T]:
T extends ConditionType ? TypeIfTrue : TypeIfFalse;
};

Example: The below code implements the mapped types to create an interface with conditional types.




type Fruit = 'apple' | 'banana';
 
type FruitProperties<T extends string[]> = {
    [P in T[number]]: P extends 'apple' ?
    { color: string } : { length: number };
};
 
interface FruitInfo extends
    FruitProperties<Fruit[]> { }
 
const appleInfo: FruitInfo = {
    apple: { color: 'red' }
} as FruitInfo;
 
const bananaInfo: FruitInfo = {
    banana: { length: 10 }
} as FruitInfo;
 
console.log(appleInfo);
console.log(bananaInfo);

Output:

{ apple: { color: red } } 
{ banana: { length: 10 } }

Article Tags :