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
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.
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?
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:
T
that extends from any object that has a length
property of type number.T
as a parameter.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 }'.
The extension of native methods offers us several advantages:
When extending native methods, we must take into account some considerations:
To implement effective extensions in TypeScript, we can follow these steps:
extends
keyword to ensure that only compatible types are accepted.// 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
Want to see more contributions, questions and answers from the community?