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
13 Hrs
16 Min
40 Seg
Curso de TypeScript

Curso de TypeScript

Amin Espinoza

Amin Espinoza

Uso de extends, sobreescritura de métodos en TypeScript

12/26
Resources

Class inheritance in TypeScript is a powerful feature that allows you to extend the functionality of existing classes without modifying their original code. This fundamental technique of object-oriented programming allows you to create more organized class hierarchies and reuse code efficiently, saving time and reducing the possibility of errors in your projects.

How to extend classes in TypeScript?

Class extension in TypeScript allows us to create a new class that inherits all the properties and methods of a base class, adding new functionality without modifying the original class. This is achieved by means of the keyword extends.

To illustrate this concept, we will start with a base class called Person that contains basic properties such as name, age and whether it is a developer:

export class Person { constructor( public name: string, public age: number, public isDeveloper: boolean ) {}}

Now, to extend this class and create a new one called Employee, we follow these steps:

  1. Create a new file called employee.ts
  2. Import the base class Person
  3. We use the extends keyword to inherit from Persona
import { Persona } from './persona';
export class Employee extends Persona { constructor( name: string, age: number, isDeveloper: boolean, public job: string ) { super(name, age, isDeveloper); }    
 greet() { return `Hello, I work as ${this.job}`; }    
 getInfo() { return `Iam ${this.age} years old and work as ${this.job}`; } }}

What happens in the constructor of the derived class?

The constructor of the derived class(Employee) must call the constructor of the base class(Person) using the super() keyword. This call is mandatory and must be made before accessing any property with this inside the constructor.

In our example:

  • We receive the original parameters (name, age, isDeveloper).
  • We add a new parameter (position)
  • We call super() with the parameters needed by the base class
  • We define the new post property as public

It is important to note that the derived class inherits all the properties and methods of the base class, but it can also:

  • Add new properties (such as post)
  • Add new methods (such as greet() and getInfo())
  • Override methods of the base class (if necessary).

How to use extended classes?

Once we have created our class hierarchy, we can use them in our main code. To do this, we create a main.ts file:

import { Employee } from './employee';
const employee = new Employee('John', 30, true, 'Frontend Developer');
console.log(employee.greet());console.log(employee.getInfo());console.log(employee.name);

When executing this code, we will get:

  • "Hi, I work as a Frontend Developer".
  • "I am 30 years old and I work as a Frontend Developer."
  • "Juan"

Cascading compilation

An interesting feature of TypeScript is cascading compilation. When we compile a file that imports other files, TypeScript automatically compiles all dependent files.

For example, when you run:

tsc main.ts

TypeScript will compile:

  1. main.ts (the file we specify).
  2. employee.ts (because main.ts imports it)
  3. person.ts (because employee.ts imports it)

This generates the corresponding JavaScript files(main.js, employee.js, person.js) without the need to compile each one manually. This feature saves time and ensures that all dependencies are correctly compiled.

Why use class inheritance?

Class inheritance offers multiple benefits:

  • Code reuse: avoids duplicating common properties and methods.
  • Hierarchical organization: allows the creation of logical object structures
  • Maintainability: facilitates changes in the base class that propagate to all derived classes
  • Extensibility: allows you to add functionality without modifying the original code

Inheritance is especially useful when working with objects that share common characteristics but need specific additional functionality.

Class inheritance in TypeScript is a powerful tool that allows you to create more organized, maintainable and extensible code. Mastering this technique will help you develop more robust applications and take full advantage of object-oriented programming in your TypeScript projects.

Have you used class inheritance in your projects? What other object-oriented programming techniques do you consider fundamental? Share your experience in the comments.

Contributions 4

Questions 0

Sort by:

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

El concepto de `extends` en TypeScript se utiliza para crear una nueva clase que hereda propiedades y métodos de una clase base. Al usar `extends`, puedes reutilizar el código de la clase padre y agregar nuevas propiedades o métodos a la clase hija. Esto se alinea con el principio de la programación orientada a objetos que promueve la reutilización y la organización del código. La sobreescritura de métodos ocurre cuando una clase hija redefine un método de la clase padre. Esto permite que el método de la clase hija tenga un comportamiento específico que puede diferir del método original. Para sobrescribir un método, simplemente defines un método con el mismo nombre en la clase hija. Un ejemplo simple sería: ```typescript class Persona { saludar(): string { return "Hola"; } } class Empleado extends Persona { saludar(): string { return "Hola, soy un empleado"; } } const empleado = new Empleado(); console.log(empleado.saludar()); // "Hola, soy un empleado" ``` En este caso, el método `saludar` de `Empleado` sobrescribe el método `saludar` de `Persona`. Al llamar a `saludar` en una instancia de `Empleado`, se ejecuta la versión sobrescrita. Esto permite personalizar el comportamiento de la clase hija mientras se mantiene la estructura de la clase base.
Lo entendí mejor con un esquema que hice ![](https://static.platzi.com/media/user_upload/image-5e4adaab-f003-4dc2-acc7-ec54eb9d08d3.jpg)
Como dato, se puede extender la clase Error nativo: ```js export class AnimalError extends Error { constructor(message: string) { super(message); this.name = "AnimalError"; } } ```
Características de la ***POO***: · **Clases y Objetos:** \+ **Clase:** Es una plantilla o modelo que define las características y comportamientos de un grupo de objetos. \+ **Objeto:** Es una instancia de una clase, con sus propios datos y comportamientos. · **Encapsulación:** Agrupa datos y métodos relacionados en una unidad (clase), protegiendo la integridad de los datos y controlando el acceso a ellos. · **Herencia:** Permite que una clase (clase hija) herede propiedades y métodos de otra clase (clase padre), facilitando la reutilización de código. La extensión de clases en TypeScript nos permite crear una nueva clase que hereda todas las propiedades y métodos de una clase base, añadiendo nuevas funcionalidades sin modificar la clase original. Esto se logra mediante la palabra clave `extends`.