DEV Community

Cover image for Unions and Intersection Types en TypeScript
Juan Delgado
Juan Delgado

Posted on

Unions and Intersection Types en TypeScript

Soy una nota nice

A veces debemos de admitir parámetros en una funcion donde el tipo de parametro puede ser por ejemplo String o Number :

function padLef(value: string, padding: any) {
    if (typeof padding === "number") {
        return Array(padding + 1).join(" ") + value;
    }
    if (typeof padding === "string") {
        return  `${value} ${padding}`;
    }
    throw new Error(`Solo se admiten tipos de valores string o number, no se aceptan ${padding}`)
}

console.log(padLef("Hola mundo", 10));

El problema de declarar el parametro padding como any es que recibe cualquier tipo de valor ya sea true* o hasta un **Array y el compilador de Typescript lo aceptara sin problemas.

Para solucionar este problema utilizaremos las uniones de Typescript, donde solo se aceptaran los tipos que se declaren en el parámetro, no hay limite de uniones puedes utilizar 2 o mas uniones si es necesario:

function padLeft(value: string, padding: string | number) {
  // ...
}

let indentedString = padLeft("Hello world", true);

El compilador de Typescript nos dirá que no se puede aceptar valores Booleanos porque en el parametro solo aceptan valores de tipo string o number

Sindicatos discriminantes

Una técnica común para trabajar con uniones es tener un solo campo que use tipos literales que puede usar para permitir que TypeScript reduzca el posible tipo actual. Por ejemplo, vamos a crear una unión de tres tipos que tienen un solo campo compartido.

type NetworkLoadingState = {
    state: "loading";
  };

  type NetworkFailedState = {
    state: "failed";
    code: number;
  };

  type NetworkSuccessState = {
    state: "success";
    response: {
      title: string;
      duration: number;
      summary: string;
    };
  };

  // Crea un tipo que representa sólo uno de los tipos anteriores
  // pero aún no estás seguro de cuál es.
  type NetworkState =
    | NetworkLoadingState
    | NetworkFailedState
    | NetworkSuccessState;

Todos los tipos anteriores tienen un campo llamado state, y luego también tienen sus propios campos. Dado que el campo state es común en todos los tipos internos NetworkState, es seguro para su código acceder sin una verificación de existencia.

Quadratic AI

Quadratic AI – The Spreadsheet with AI, Code, and Connections

  • AI-Powered Insights: Ask questions in plain English and get instant visualizations
  • Multi-Language Support: Seamlessly switch between Python, SQL, and JavaScript in one workspace
  • Zero Setup Required: Connect to databases or drag-and-drop files straight from your browser
  • Live Collaboration: Work together in real-time, no matter where your team is located
  • Beyond Formulas: Tackle complex analysis that traditional spreadsheets can't handle

Get started for free.

Watch The Demo 📊✨

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay