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
14 Hrs
51 Min
49 Seg
Curso de TypeScript

Curso de TypeScript

Amin Espinoza

Amin Espinoza

Restricciones con extends, genéricos en interfaces

14/26
Resources

The functionality extension in TypeScript is a powerful tool that allows us to enhance the native methods of the language, adapting them to our specific needs. This capability not only allows us to customize our own classes, but also to extend the functionality of the methods built into the language.

How to extend native methods in TypeScript?

TypeScript allows us to go beyond the simple creation of custom classes. With the reserved word extends, we can extend the functionality of methods that come built into the language. This gives us the ability to obtain additional information or modify the behavior of frequently used functions.

To better understand this concept, let's analyze a practical example. Let's imagine that we want to improve the functionality of the default length property of strings and arrays.

// We declare a variable of type stringconst name: string = "John";
// We use the native length propertyconsole.log(name.length); // Result: 4

In this example, we are using the length property that is built into the string type. This property returns the number of characters in the string. However, what if we wanted to get more information besides the length?

Creating an extended function with generics

We can create a function that extends the functionality of length using generic types:

// Function extending the functionality of lengthfunction getLength<T extends { length: number }>(obj: T): number { // We get the length of the object const length: number = obj.length;  
 // We get the type of the object const type: string = typeof obj;  
 // We display additional information console.log(`Thedata type is ${type} and the length of this data is ${length}`);  
 // We return the original length return obj.length;}

In this function:

  1. We use a generic type T that extends from any object that has a length property of type number.
  2. We receive an object of type T as a parameter.
  3. We get the length of the object and its type.
  4. We display this additional information.
  5. We return the original length.

Applying our extended function

Now we can use our function with different data types that have the length property:

// With a stringconsole.log(getLength("hello")); // 4// It will also display: "The data type is string and the length of this data is 4"
// With an arrayconsole.log(getLength([1, 2, 3, 4, 4, 5])); // 5// It will also display: "The data type is object and the length of this data is 5"

It is important to note that this function will only work with types that have the length property. If we try to use it with a number, for example, we will get an error:

// This will generate an errorconsole.log(getLength(42)); // Error: argument of type 'number' is not assignable to parameter of type '{ length: number }'.

Why is it useful to extend native methods?

The extension of native methods offers us several advantages:

  • More information: we can obtain additional data that the original method does not provide.
  • Customization: We adapt the functionality to our specific needs.
  • Consistency: We maintain the original functionality while adding our improvements.
  • Reusability: We create functions that we can use in different parts of our application.

Important considerations

When extending native methods, we must take into account some considerations:

  • Compatibility: Make sure that the data type we are working with has the property we want to extend.
  • Clear purpose: Have a defined goal for the extension, not just extend for the sake of extending.
  • Maintainability: Extensions must be easy to maintain and understand for other developers.

How to implement effective extensions?

To implement effective extensions in TypeScript, we can follow these steps:

  1. Identify the need: Determine what functionality we want to enhance or extend.
  2. Use generic types: Take advantage of generics to make our extensions more flexible.
  3. Restrict types: Use the extends keyword to ensure that only compatible types are accepted.
  4. Maintain original functionality: Do not modify the expected behavior of the original method.
  5. Add value: Ensure that our extension provides useful additional information or functionality.
// Example of a more elaborate extensionfunction parseCollection<T extends { length: number }>(collection: T) { const length = collection.length; const type = typeof collection; const isEmpty = length === 0;  
 return { length, type, isEmpty, summary: `Collectionof type ${type} with ${length} elements. ${isEmpty ? 'Is empty.'  : 'It is not empty.'}` };}

Native method extension in TypeScript is a powerful tool that allows us to customize and enhance the functionality of the language. By mastering this technique, we can create more robust applications tailored to our specific needs. Have you used extensions in your projects? Share your experiences and how you have taken advantage of this TypeScript feature.

Contributions 2

Questions 0

Sort by:

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

Por cierto, **extender** `length` **no significa modificarlo ni agregarlo a tipos que no lo tienen**, como `number`. No puedes cambiar cómo funciona `length` en `string` o `array`, ni hacer que un número tenga una propiedad `length`. En realidad, lo que hacemos es **aprovechar** `length` **en funciones y clases sin alterar su comportamiento original**, como en una función genérica que reciba cualquier objeto con `length` y nos dé información extra sobre él
les dejo una imagen para que entiendan mejor la función![](https://static.platzi.com/media/user_upload/image-e99781a8-2bf4-4d42-b98e-501b794de1f6.jpg)