In TypeScript, you can combine enums, types and interfaces in various ways to create complex and precise data structures.
Enums in interfaces
We could associate the typing of one of the properties of an interface
with an enum
:
enum Color {Black, White, Purple } interface GeometricFigure { name: string; color: Color; } const rectangle: GeometricFigure = { name: "rectangle", color: Color.Purple };
Types in Interfaces
In the attributes of an interface
we could use a type
to give a customizable type:
type Coordinates = [number, number]; interface Point { location: Coordinates; label: string; }const point: Point = { location: [10, 5], label: "Point A"};
Combining Enums and Types
In TypeScript, it is also possible to put enums and types together. For example, we can declare a type
that has the object structure in which one of its properties is a value from the options set belonging to an enum
:
{enum Size {Small = "S", Medium = "M", Large = "L"}type Product = { name: string; size: Size; // 👈 Enum }; const t-shirt: Product = { name: "T-shirt", size: Size.Medium };
Interfaces, enums and types together
It is possible to use enums and types within an interface
to create a single complex structure in order to generate objects with more detailed and precise information:
enum VehicleType { Automobile, Motorcycle } type Specifications = { make: string; model: string; model: string;year: number; }; interface Vehicle { type: VehicleType; Specifications: Specifications; }const vehicle: Vehicle = { type: TypeVehicle.Automobile, specifications: { brand: "Toyota", model: "Corolla",year: 2020} };
By combining these structures, you have the ability to produce more complex data structures and set more detailed types for your objects and variables. This results in code that is clearer, safer, and easier to maintain.
Contributed by: Martin Alvarez (Platzi Contributor).
Want to see more contributions, questions and answers from the community?