Fundamentos de TypeScript

1

驴Qu茅 es TypeScript y por qu茅 usarlo?

2

Instalaci贸n de Node.js y TypeScript CLI, configuraci贸n de tsconfig.json

3

Tipos primitivos: string, number, boolean, null, undefined de Typescript

4

Tipos especiales: any, unknown, never, void de TypeScript

5

Arrays, Tuplas, Enums en TypeScript

Funciones e Interfaces

6

Declaraci贸n de funciones, tipado de par谩metros y valores de retorno

7

Par谩metros opcionales, valores por defecto y sobrecarga de funciones

8

Creaci贸n y uso de interfaces de TypeScript

9

Propiedades opcionales, readonly, extensi贸n de interfaces en TypeScript

Clases y Programaci贸n Orientada a Objetos

10

Creaci贸n de clases y constructores En TypeScript

11

Modificadores de acceso (public, private, protected) en Typescript

12

Uso de extends, sobreescritura de m茅todos en TypeScript

13

Introducci贸n a Gen茅ricos en Typescript

14

Restricciones con extends, gen茅ricos en interfaces

M贸dulos y Proyectos

15

Importaci贸n y exportaci贸n de m贸dulos en TypeScript

16

Agregando mi archivo de Typescript a un sitio web

17

Configuraci贸n de un proyecto Web con TypeScript

18

Selecci贸n de elementos, eventos, tipado en querySelector en TypeScript

19

Crear un proyecto de React.js con Typescript

20

Crea un proyecto con Angular y Typescript

21

Crea una API con Typescript y Express.js

Conceptos Avanzados

22

Introducci贸n a types en TypeScript

23

Implementaci贸n de Decoradores de TypeScript

24

Async/await en Typescript

25

Pruebas unitarias con Jest y TypeScript

26

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

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
5 Hrs
26 Min
5 Seg
Curso de TypeScript

Curso de TypeScript

Amin Espinoza

Amin Espinoza

Propiedades opcionales, readonly, extensi贸n de interfaces en TypeScript

9/26
Resources

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.

How to implement optional properties in interfaces

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"};

How to create read-only properties in interfaces?

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.

How to extend interfaces to reuse 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:

  • Reduce code duplication
  • Maintain a clear and organized structure
  • Facilitate future changes, since modifications to the base interface are automatically propagated to all the interfaces that extend it.

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

Sort by:

Want to see more contributions, questions and answers from the community?

Las interfaces b谩sicamente sirven para definir estructuras, tipar funciones y reutilizar c贸digo.
Un caso de uso real del modificador `readonly` en TypeScript es en la definici贸n de objetos de configuraci贸n. Supongamos que est谩s creando una aplicaci贸n de gesti贸n de usuarios. Podr铆as definir una interfaz para representar la configuraci贸n del usuario de la siguiente manera: ```typescript interface UserConfig { readonly username: string; readonly email: string; readonly createdAt: Date; } const userConfig: UserConfig = { username: "usuario123", email: "[email protected]", createdAt: new Date() }; // userConfig.username = "nuevoUsuario"; // Esto causar铆a un error ``` Aqu铆, `readonly` asegura que los valores de `username`, `email` y `createdAt` no puedan ser modificados despu茅s de que se inicializan, lo que es 煤til para mantener la integridad de la configuraci贸n a lo largo del tiempo.