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