DEV Community

Cristian Fernando
Cristian Fernando

Posted on • Edited on

4 2

Fundamentos de TypeScript 🦆| #4: Tuplas

Las tuplas en esencia son arreglos, pero arreglos limitados a cierta cantidad de elementos y a ciertos tipos de datos.

Sintaxis

const nombreVariable:[tipoDato1, tipoDato2, ...tipoDatoN] = [valor1, valor2, ... valorN];
Enter fullscreen mode Exit fullscreen mode

Funcionamiento

Por ejemplo, podríamos tener una tupla temperatura de 2 posiciones, que contega la temperatura y su unidad de medida:

const temperatura:[number, string] = [20,"C"];
Enter fullscreen mode Exit fullscreen mode

Esta tupla solo puede contener 2 elementos, el primero un number, y el segundo un string, exactamente en ese orden.
Si tuvieramos la tupla invertida tendríamos un error:

const temperatura:[number, string] = ["C", 20];
Enter fullscreen mode Exit fullscreen mode

Estamos tratando de asignar un tipo string a un tipo number, por ello nos arroja una advertencia como la siguiente:

Type 'string' is not assignable to type 'number'.

Ahora, si intentamos agregar más de 2 elementos al ejemplo anterior, por más que sean del tipo de dato permitido, este arrojará un error:

const temperatura:[number, string] = [20, "C", 23, "F"];
Enter fullscreen mode Exit fullscreen mode

Type '[number, string, number, string]' is not assignable to type '[number, string]'.
Source has 4 element(s) but target allows only 2.

Para solucionarlo tendremos que añadir más tipos, de la siguiente manera:

const temperatura:[number, string, number, string] = [20, "C", 23, "F"];
Enter fullscreen mode Exit fullscreen mode

Caso especial

¿Qué pasaría si intentamos usar un push en una tupla?
¿Debería dar un error no es verdad?
Pues no lo hace.

const temperatura:[number, string, number, string] = [20, "C", 23, "F"];

temperatura.push(30)
//salida: [20, "C", 23, "F", 30];
Enter fullscreen mode Exit fullscreen mode

Este ejemplo es totalmente válido.


Conclusiones

  • Las tuplas son arreglos pero son datos específicos.
  • Permiten crear arreglos con valores concretos y tipos exactos en cuanto a posiciones se refiere.
  • Son más rápidos que los arreglos tradicionales.

Referencias

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more