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:

2 D铆as
17 Hrs
40 Min
53 Seg
Curso de TypeScript

Curso de TypeScript

Amin Espinoza

Amin Espinoza

Arrays, Tuplas, Enums en TypeScript

5/26
Resources

Data collections in TypeScript are essential for handling multiple values in a structured and efficient way. When working with real applications, we need to organize related information, and TypeScript provides powerful tools to do this with type safety, which reduces errors and improves code maintainability.

How to work with data collections in TypeScript?

When we have multiple variables of the same type, we can group them into collections. TypeScript offers several ways to work with these collections, each with specific features that suit different needs.

What are arrays and how are they implemented?

Arrays are the most common form of collection in TypeScript. They allow multiple values of the same type to be stored in a single variable.

To declare an array of strings:

let names: string[] = ["Anna", "John", "Mary"];console.log(names);

We can also create arrays of numbers:

let ages: number[] = [39, 25, 30];console.log(ages);

An important feature of arrays is that they can be modified at run time, adding or removing elements as needed.

How to work with arrays of type any?

If we need flexibility in the types of data we store, we can use arrays of type any:

let mixed: any[] = ["Hello", 42, true];console.log(mixed);

This type of array can contain any data type, which is useful in certain scenarios, but sacrifices the type safety that TypeScript provides.

What are interface arrays?

When we need more complex data structures, we can create arrays based on interfaces:

interface Person { name: string; age: number; developer: boolean;}
let persons: Person[] = [ { { name: "Avin", age: 30, developer: true }];
// We can add interface-compliant elementspersons.push({ name: "Miranda", age: 28, developer: true});
console.log(persons);

These arrays ensure that all elements have the same structure, which makes the code more predictable and easier to maintain.

What are tuples and how do they differ from arrays?

Tuples are collections with a fixed number of elements, where each item can have a specific type:

let personTuple: [string, number, boolean] = ["Avin", 30, true];console.log(personTuple);

The crucial difference between tuples and arrays is that tuples cannot be modified after their creation. Once defined, their structure remains immutable, which provides greater security in certain scenarios.

To step through the elements of a tuple, we can use a forEach loop:

let [name, age, developer] = personTuple;console.log(name);console.log(age);console.log(developer);

How to use enumerators to limit values?

Enumerators (enums) are a powerful feature that allows you to define a set of named constants:

enum DayWeek { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}
let day: DayWeek = DayWeek.Sunday;console.log(day); // Sample: 6 (numeric index)console.log(DayWeek[day]); // Sample: "Sunday" (name).

Enumerators are especially useful for limiting the available options and making the code more readable. If we try to assign a value that is not in the enumerator, TypeScript will display an error:

// This would generate an error// let diaInvalid: DayWeek = DayWeek.January;

Why are typed collections important in TypeScript?

The use of typed collections in TypeScript offers multiple advantages:

  • Error prevention: the type system detects inconsistencies before executing code.
  • Better documentation: The type of a collection clearly communicates what data it contains.
  • Improved auto-completion: Editors can provide more accurate suggestions.
  • Safer refactoring: Changes to the data structure are propagated throughout the code.

Working with data collections in TypeScript is more comfortable thanks to strong typing. This avoids common problems such as inadvertently mixing data types, making our applications more robust and structured.

Typed collections are a fundamental tool for any developer looking to write more maintainable and less error-prone code. Have you experimented with these different ways of handling collections in your projects? Share your experiences and doubts in the comments.

Contributions 5

Questions 0

Sort by:

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

**馃挕Recordemos que es una interfaz o interface:**Es una forma de definir la estructura de un objeto, y como TS es tipado es muy 煤til ya que nos permite establecer que propiedades y tipos debe tener un objeto sin necesidad de inicializarlo. Tiene beneficios como: * Definir la forma de los objetos para que tengan propiedades espec铆ficas. * Facilitar la reutilizaci贸n de c贸digo * Ayuda a la validaci贸n de errores de tipo.
Investigando un poco, descubr铆 que los `enum` en TypeScript pueden ser problem谩ticos porque sus valores no son inmutables, pueden tener indexaci贸n inversa que genera valores inesperados y adem谩s producen m谩s c贸digo en JavaScript del necesario. La mejor soluci贸n es usar un objeto con `as const`, ya que esto mantiene los valores estrictos, inmutables y sin sobrecarga extra en el c贸digo. En lugar de `enum Role { ADMIN = "ADMIN", USER = "USER" }`, es mejor usar `const ROLES = { ADMIN: "ADMIN", USER: "USER" } as const;`, y definir su tipo con `type Role = typeof ROLES[keyof typeof ROLES];`, asegurando as铆 una estructura m谩s segura y eficiente.
Una manera de manejar tipos din谩mico en TypeScript sin tener que usar `any` o `unknown` es crear arrays que acepten m谩s de un tipo espec铆fico mediante el uso de un tipo de uni贸n. Por ejemplo, puedes declarar un array que contenga tanto n煤meros como cadenas de la siguiente manera: `let mixedArray: (number | string)[] = [1, 'dos', 3];` Esto permite que el array contenga elementos de diferentes tipos, sin utilizar `any` o `unknown`. Adem谩s, este tipo de array tiene una longitud din谩mica, lo que lo diferencia de las tuplas, que tienen una longitud fija y tipos definidos para cada posici贸n.
![](https://static.platzi.com/media/user_upload/imagen-88ddf009-d227-42e0-9afd-38a88654805f.jpg)
otro ejemplo para usar `enums` es:enum ROLES { ADMIN = "ADMINS", VENDEDOR = "VENDEDOR", CUSTOMER = "CUSTOMER" } let userRole = ROLES.ADMIN //Devuelve "ADMINS" ```js enum ROLES { ADMIN = "ADMINS", VENDEDOR = "VENDEDOR", CUSTOMER = "CUSTOMER" } let userRole = ROLES.ADMIN //Devuelve "ADMINS" ```