Fundamentos de TypeScript
驴Qu茅 es TypeScript y por qu茅 usarlo?
Instalaci贸n de Node.js y TypeScript CLI, configuraci贸n de tsconfig.json
Tipos primitivos: string, number, boolean, null, undefined de Typescript
Tipos especiales: any, unknown, never, void de TypeScript
Arrays, Tuplas, Enums en TypeScript
Funciones e Interfaces
Declaraci贸n de funciones, tipado de par谩metros y valores de retorno
Par谩metros opcionales, valores por defecto y sobrecarga de funciones
Creaci贸n y uso de interfaces de TypeScript
Propiedades opcionales, readonly, extensi贸n de interfaces en TypeScript
Clases y Programaci贸n Orientada a Objetos
Creaci贸n de clases y constructores En TypeScript
Modificadores de acceso (public, private, protected) en Typescript
Uso de extends, sobreescritura de m茅todos en TypeScript
Introducci贸n a Gen茅ricos en Typescript
Restricciones con extends, gen茅ricos en interfaces
M贸dulos y Proyectos
Importaci贸n y exportaci贸n de m贸dulos en TypeScript
Agregando mi archivo de Typescript a un sitio web
Configuraci贸n de un proyecto Web con TypeScript
Selecci贸n de elementos, eventos, tipado en querySelector en TypeScript
Crear un proyecto de React.js con Typescript
Crea un proyecto con Angular y Typescript
Crea una API con Typescript y Express.js
Conceptos Avanzados
Introducci贸n a types en TypeScript
Implementaci贸n de Decoradores de TypeScript
Async/await en Typescript
Pruebas unitarias con Jest y TypeScript
Principios SOLID, c贸digo limpio, patrones de dise帽o en Typescript
You don't have access to this class
Keep learning! Join and start boosting your career
Implementing interfaces in TypeScript is a powerful tool that allows you to structure and organize your code efficiently. By defining clear contracts for your objects, interfaces help you catch bugs early and create more maintainable code. In this article, we will explore how to implement different types of properties in interfaces and how to extend them to maximize code reuse.
Interfaces in TypeScript not only allow us to define the structure of our objects, but also provide flexibility through optional properties. These properties are identified by a question mark (?) after the property name.
Let's see a practical example:
interface Address { street: string; number: number; city?: string;}
In this interface, city
is an optional property thanks to the question mark. This means that we can implement this interface in two different ways:
// Implementation without the optional propertyconst address: Address = { street: "Fake Street", number: 123};
// Implementation including the optional propertyconst addressComplete: Address = { street: "Fake Street", number: 123, city: "Springfield"};
The advantage of optional properties is that they allow us to create flexible structures that adapt to different contexts without generating errors. However, it is important to remember that properties not marked as optional are still mandatory.
If we try to create an object that omits a mandatory property, TypeScript will display an error immediately:
// This will generate an errorconst incorrectaddress: address = { street: "Fake Street", // Error: property 'number' is mandatory city: "Springfield"};
Another powerful feature of interfaces in TypeScript is the ability to define read-only properties using the readonly
keyword. These properties can only be assigned when the object is created and cannot be modified later.
interface PersonReadOnlyinterface { readonly name: string; readonly age: number; readonly isDeveloper: boolean;}
By implementing this interface, we can assign initial values to all properties:
const personaRead: personaReadOnly = { name: "Amin", age: 30, isDeveloper: true};
However, if we try to modify any of these properties after initialization, TypeScript will show us an error:
// This will generate an errorpersonaRead.name = "Marce"; // Error: Cannot assign to 'name' because it is a read-only property.
Read-only properties are especially useful when we want to ensure that certain values remain constant throughout the lifetime of an object, thus providing greater security and predictability in our code.
One of the most powerful features of interfaces in TypeScript is the ability to extend them. This allows us to create new interfaces based on existing interfaces, inheriting all their properties and adding new ones.
interface Person { readonly name: string; readonly age: number; readonly isDeveloper: boolean;}
interface Employee extends Person { job: string;}
In this example, the interface Employee
extends the interface Persona
, which means that it inherits all the properties of Persona
(name
, age
and isDeveloper
) and adds a new property: job
.
Now we can implement the Employee
interface:
const employee: Employee = { name: "Amin", age: 30, isDeveloper: true, job: "Senior Developer"};
The extension of interfaces is extremely useful for modeling hierarchical relationships between different entities in our domain. Instead of duplicating common properties across multiple interfaces, we can define them once and extend them as needed.
This technique allows us to:
Implementing interfaces with optional, read-only properties and extending interfaces are powerful tools that will help you write cleaner, more maintainable and scalable TypeScript code. The more you practice with these techniques, the more you will appreciate how they help you save time and avoid errors in your projects, especially as they grow in complexity and size.
Have you used interfaces in your TypeScript projects, and what techniques have you found most useful for organizing your code? Share your experience in the comments.
Contributions 2
Questions 1
Want to see more contributions, questions and answers from the community?