Interfaces & Aliases
Use interfaces and aliases to define types separately from the implementation of variables themselves. This allows you to reuse types across multiple variables and objects. Interfaces are used to define object types, while aliases can be used to define any type.
Type Aliases
Define types with custom names. Can be used to define any type, such as primitives, arrays, and objects.
type VehicleYear = number;
type VehicleMaker = string;
type VehicleModel = string;
type Vehicle = {
year: VehicleYear;
maker: VehicleMaker;
model: VehicleModel;
};
const vehicleYear: VehicleYear = 2008;
const vehicleMaker: VehicleMaker = 'Honda';
const vehicleModel: VehicleModel = 'Civic';
const vehicle: Vehicle = {
year: vehicleYear,
maker: vehicleMaker,
model: vehicleModel,
};
Interfaces
Interfaces can only be used to define object types.
interface Rectangle {
height: number;
width: number;
}
const rectangle: Rectangle = {
height: 22,
width: 11,
};
Extending Interfaces
Interfaces can be used to extend other interfaces. This allows you to reuse common properties across multiple interfaces.
interface Rectangle {
height: number;
width: number;
}
interface ColorRectangle extends Rectangle {
color: string;
}
const colorRectangle: ColorRectangle = {
height: 22,
width: 11,
color: 'green',
};