What is the process of converting a union type into a union of arrays in TypeScript?

I have a Foo type that consists of multiple types

For example:

type Foo = string | number

I need to receive this type and convert it into an array of the individual types within the union

type TransformedFoo = ToUnionOfArray<Foo> // => string[] | number[]

Simply using Foo[] won't work in this case, since it would result in (string | number)[].

What's the best way to turn a union type into an array of its constituent types?

Answer №1

To leverage distributive conditional types, you can utilize the following syntax:

type Bar = boolean | number;

type Lists<U> = U extends any ? U[] : never;

type ModifiedBar = Lists<Bar>; // boolean[] | number[]

Interactive Example

Conditional types turn into distributive forms when operating on a generic type within a union

Answer №2

To handle this situation, you can utilize distributive conditionals like so:

type ConvertToUnion<T> = T extends infer U ? U[] : never;

When the type parameter T is used in a conditional statement without any constraints, the conditional will be applied (or distributed) to each value within the input union T.

For more information on how this concept operates, check out this resource: Typescript Distributive Conditional Types

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Getting an error in Typescript: 'Operator '!==' cannot be used with types' while working with enums

When comparing enums, I encountered a perplexing error message stating "Operator '!==' cannot be applied to types," whereas the same comparison with integer values did not result in an error: enum E { A, B, C, D, E, F } ...

Yelp API call resulting in an 'undefined' response

When attempting to make an API call using the yelp-fusion, I noticed that the logged result is showing as undefined. It seems like this issue might be related to promises or async functions. It's important for me to maintain this within a function sin ...

Learn how to set up browser targeting using differential loading in Angular 10, specifically for es2016 or newer versions

Seeking advice on JS target output for compiled Angular when utilizing differential loading. By default, Angular compiles TypeScript down to ES5 and ES2015, with browsers using either depending on their capabilities. In order to stay current, I've b ...

A method for comparing two arrays containing identical objects and then storing the results in a variable

I have an item stored within two other items called formKeyValues and form formKeyValues https://i.stack.imgur.com/nRfiu.png form https://i.stack.imgur.com/eDpid.png I am looking to extract only the keys and values from formKeyValues and place them in ...

Is it possible to efficiently share sessionStorage among multiple tabs in Angular 2 and access it right away?

My Current Knowledge: I have discovered a way to share sessionStorage between browser tabs by using the solution provided here: browser sessionStorage. share between tabs? Tools I Am Using: Angular 2 (v2.4.4) with TypeScript on Angular CLI base The ...

Exploring the Observable object within Angular

As I delve into learning Angular through various tutorials, I encountered a perplexing issue regarding my console displaying an error message: ERROR in src/app/employee/employee.component.ts:17:24 - error TS2322: Type 'IEmployee' is not assignab ...

How to extract the chosen option from a bound list within an Angular application

Our goal is to avoid using 2-way binding in our component setup: <select type="text" formControlName="region" (change)="regionChanged($event)"> <option *ngFor="let region of regionsDDL" [ngValue]="region">{{region.name}}</option> ...

The type 'Observable<false>' cannot be assigned to the type 'Observable<boolean>'

Our team had been using Knockout.js (v3.5.0) along with its TypeScript definitions without any issues until TypeScript 4.6.2 came along. It seems that the problem goes beyond just the definitions file, possibly due to a change in how TypeScript handles boo ...

Is there a way to render a component without having to render AppComponent constantly?

I am looking to display two components (AppComponent and UserComponent) without constantly displaying AppComponent. Here's how my code is structured: app.routing.module.ts const routes: Routes = [ { path: '', component: AppComponent ...

Adjust the transparency and add animation effects using React JS

When working on a React project, I encountered an issue where a square would appear under a paragraph when hovered over and disappear when no longer hovered. However, the transition was too abrupt for my liking, so I decided to implement a smoother change ...

Choosing a single item from multiple elements in React using React and typescript

In this particular project, React, TypeScript, and ant design have been utilized. Within a specific section of the project, only one box out of three options should be selected. Despite implementing useState and toggle functionalities, all boxes end up bei ...

What are the steps to transpile NextJS to es5?

Is it possible to create a nextjs app using es5? I specifically require the exported static javascript to be in es5 to accommodate a device that only supports that version. I attempted using a babel polyfill, but after running es-check on the _app file, ...

ngx-charts-pie-chart angular5 library data structure

I am utilizing the ngx-charts library in my current project. When using the onSelect method, I noticed that it only returns an object with attributes value and name, even though my list contains three attributes: value, name, and id. Upon examining the s ...

"Converting array into a string in TypeScript/Javascript, but unable to perform operations

After generating a string with the correct structure that includes an array, I am able to navigate through the JSON on sites like However, when attempting to access the array, it turns out that the array itself is null. Here is the scenario: Firstly, th ...

Angular sets the required property only when the button is clicked

Is there a way to make a field required in Angular only when a button is clicked? Currently, the error message appears even before the user interacts with the field. I would like the error message "folder name is required" to only appear when the user cli ...

Trouble loading Styled Components in React Typescript with Webpack configuration

Hey there! I'm diving into the world of styled components for the first time, and I'm a bit lost on where I might have slipped up. I've got my webpack all sorted out and my .babelrc file in place. As I was going through the Styled Component ...

The circular reference error message "Redux Action 'Type alias 'Action' circularly references itself" appears

I am currently working with two different actions: export const addToCart = (id: string, qty: number) => async ( dispatch: Dispatch, getState: () => RootState ) => { const { data }: { data: IProduct } = await axios.get(`/api/products/${id}`) ...

Is it possible to define a data type from an external package using TypeScript and Node.js?

I'm currently in the process of reorganizing some code to utilize a list of signals and connect `.once` handlers to each one individually. const terminationSignals = ["SIGINT", "SIGUSR2", "SIGTERM"]; terminationSignals.f ...

Choose one of the options provided by the radio button that best fits the question using Playwright

Can Playwright docs be used to select a radio button answer based on the question and answer? I need to answer a series of yes/no questions. Here's the HTML structure of the survey site: <!DOCTYPE html> <html lang="en"> <bod ...

Merge two observables together to create a single observable that emits values from both sources. Only one observable will emit values

I am looking to combine two observables of type T[] obtained from httpservice. I have tried using forkJoin and zip, but they both return an Observable of type [T[], T[]]. However, I want to receive an object of type T[] as shown in the following code snip ...