TypeScript allows types to be defined independently from the variables that use them.
Aliases and interfaces enable easy sharing of types between different variables and objects.
Type aliases allow you to define types with a custom name (an alias).
Type aliases can be used for both primitive types like string and more complex types such as objects and arrays.
type CarYear = number type CarType = string type CarModel = string type Car = { year: CarYear, type: CarType, model: CarModel } const carYear: CarYear = 2001 const carType: CarType = “Toyota” const carModel: CarModel = “Corolla” const car: Car = { year: carYear, type: carType, model: carModel }; |
Interfaces are similar to type aliases but are specifically used for defining object types.
interface Rectangle { height: number, width: number } const rectangle: Rectangle = { height: 20, width: 10 }; |
Interfaces can extend one another, allowing for the augmentation of their definitions.
Extending an interface means creating a new interface that includes the properties of the original interface, along with additional properties. |
interface Rectangle { height: number, width: number } interface ColoredRectangle extends Rectangle { color: string } const coloredRectangle: ColoredRectangle = { height: 20, width: 10, color: “red” }; |