How to use extends keyword with interfaces In Javascript

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.

Javascript
interface Vehicle&lt;T&gt; {
    type: T extends 'car' ?
    'four-wheeler' : 'two-wheeler';
    wheels: T extends 'car' ? 4 : 2;
}

const car: Vehicle&lt;'car'&gt; = {
    type: 'four-wheeler',
    wheels: 4
};

const bike: Vehicle&lt;'bike'&gt; = {
    type: 'two-wheeler',
    wheels: 2
};

console.log(car);
console.log(bike);

Output:

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

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....