Generate an array that contains only one type by combining multiple types

My question involves combining different types to form a union, and I am seeking to generate a specialized utility type that produces an array with distinct types, for example:

type MyType = string | number
type ArrayOfMyType = ToArray<MyType> // -> string[] | number[], but not (string | number)[]

Answer №1

Upon investigating the solution proposed by Lishugupta652, I found it intriguing. Despite being clearly AI-generated, it functions effectively. Understanding the reasoning behind its success is more crucial than simply copy-pasting code snippets and expecting acceptance.

The functionality hinges on type distribution, a concept elaborated in this referenced article:

Type distribution [...] involves a compiler feature that applies conditionals individually to elements within generic union types, rather than as a whole.

If we directly utilize a generic union type to create a new type, such as demonstrated here:

type ToArray<T> = T[];
type MyArray = ToArray<string | number>

T[] will yield (string | number)[] since the entire union type is utilized, irrespective of its constituent items.

Enter the extends property. By employing extends, the conditional is applied to each element, with T representing the current iteration. This results in distributed typing, enabling us to achieve the desired outcome.

type ToArray<T> = T extends unknown ? T[] : never;
type MyArray = ToArray<string | number> // string[] | number[]

An exception arises with boolean types (after my investigation revealed no other exceptions), as booleans function akin to literal types encompassing two values: true and false. Consequently, distributing the generic union type produces one iteration each for true and false. Thus, an exception is necessary in this specific scenario.

type ToArray<T> = T extends boolean ? boolean[] : T extends any ? T[] : never;

type ArrayOfMyType = ToArray<string | number| boolean>; // string[] | number[] | boolean

For both true and false, the resulting type will be boolean[], as extends boolean ? evaluates true for both cases.

Answer №2

interface MyType {
    type: string | number;
}

type ConvertToArray<T> = T extends boolean ? boolean[] : T extends any ? T[] : never;

type ArrayOfMyTypes = ConvertToArray<MyType>; // string[] | number[]

Check out TypeScript playground

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

Navigating to the next page on a dynamic component in Angular 5 by

I'm uncertain if this scenario is feasible, but I have a page that fetches a list of items from an external API. There are currently 5 elements on the page, each acting as a link to its individual dynamically generated page through query strings. For ...

Creating a ref with Typescript and styled-components: A comprehensive guide

Trying to include a ref into a React component looks like this: const Dashboard: React.FC = () => { const [headerHeight, setHeaderHeight] = useState(0); const headerRef = React.createRef<HTMLInputElement>(); useEffect(() => { // @ts ...

What is the best way to connect Classes and Objects in Angular5?

Picture a study tool with flashcards and different categories. Each category has a title, while each card contains content, is linked to only one category, and is also connected to another card. How can I establish these connections in Angular 5 and Types ...

Adding a Third-Party JavaScript Plugin to Angular 7

I've been attempting to integrate the read-excel-file JavaScript plugin into my Angular 7 project. Despite following all the methods recommended on various websites, I have yet to succeed. Could anyone provide a better solution? declare var readXlsx ...

Is there a way to retrieve the value of an option passed by serverless CLI in serverless.ts file?

As I explored the serverless framework with serverless.ts for configuration, a certain question came to mind. When utilizing the serverless CLI, passing values can be done in the following way: serverless offline --stage prod In the serverless.yml file, ...

Steering clear of the generic Function type in React with TypeScript

Can anyone help me find a guideline that prohibits the use of "Function" as a type? myMethod: Function; I have searched but couldn't locate any information on this. Appreciate any suggestions :) ...

Typescript Formik typings in React Native for handling `handleSubmit` on `onPress`

Recently, I embarked on a project using React Native with Typescript and encountered Formik as my chosen tool for building forms within the application. I found the informative tutorial guide by Formik to be very helpful, especially the section on using F ...

Encountering Angular 8 error TS2304 at line 39: Cannot find the specified name after shutting down WebStorm

After working on my Angular project and closing the IDE last night, I encountered an odd problem today. The project doesn't seem to recognize certain libraries such as Int8Array, Int16Array, Int32Array... And many others. While the project is still ab ...

Issues with loading Angular 6 project in Internet Explorer 11

My Angular 6 project is successfully loading in Chrome, however it is not working in IE11. I referred to the Stack Overflow question titled Angular 2 / 4 / 5 not working in IE11 for potential solutions, but unfortunately none of them resolved the issue. He ...

MikroORM - Conditional join without foreign key constraints on the ID

I came across a rather peculiar database schema that includes a jsonb field with userId and userType attributes, along with two different user tables for distinct user types. The selection of the table to join based on the userType is crucial. Although I ...

Filter an array of objects using criteria from a separate array [TypeScript/JavaScript]

I am faced with a scenario where I have two dropdowns, each designed to filter specific keys of an object. The key feature here is that the dropdown selections should not depend on each other; in other words, filtering can occur independently based on the ...

What is the best way to transform private variables in ReactJS into TypeScript?

During my conversion of ReactJS code to TypeScript, I encountered a scenario where private variables were being declared in the React code. However, when I converted the .jsx file to .tsx, I started receiving errors like: Property '_element' d ...

Tips for managing various potential return types in TypeScript?

In my research on the topic, I came across a discussion thread about obtaining the local IP address in Node.js at Get local IP address in Node.js. In that thread, there is a code snippet that I would like to incorporate: import net from 'net'; c ...

Angular 6's tslint feature is generating duplicated warnings and errors for every issue detected

After updating to Angular 6, I've noticed that every tslint error and warning is showing up twice. The versions are Tslint 5.10.0, Angular CLI 6.0.0, Typescript 2.7.2, and Codelyzer 4.3.0. Here's an example of the duplicated errors: ERROR: file. ...

Alias for function in TypeScript declaration file (.d.ts)

There is a function within a Node module that I am trying to document in a .d.ts file. This function has two aliases, config() and load() (check the source here). The function definition in the dotenv/index.d.ts file looks like this: export function confi ...

I encountered a problem where the error "Type '(err: Error) => void' does not possess any properties similar to type 'QueryOptions'" appeared, and I am unsure of the underlying cause

Check out my route for removing a user: https://i.stack.imgur.com/fevKI.png I've set up a route called "/deleteuser" that uses the POST method. It validates the request body for an id and then proceeds to delete the user with that ID from the databas ...

Fill a dynamic form with a date sourced from the ngrx storage

How can I populate a form with data from the store if setValue and patchValue methods are not working? export class MyComponent implements OnInit, OnDestroy { public newsletterToEdit$: Observable<NewNewsletter> = this.store.selectNewsletterToEdi ...

Ensure that the query value remains constant in Express.js

Issue: The query value is changing unexpectedly. // url: "http://localhost:4000/sr?q=%C3%BCt%C3%BC" export const search = async (req: Request, res: Response) => { try { const query = String(req.query.q) console.log("query: &quo ...

Updating row values in an Angular table

I have a reusable table with the [cellData]="row" attribute to populate each cell on the table (see sample table in the screenshot). My question is, how can we replace the null values on the template with "---" so that instead of displ ...

Convert an array into a JSON object for an API by serializing it

Currently, I am working with Angular 12 within my TS file and have encountered an array response from a file upload that looks like this- [ { "id": "7", "name": "xyz", "job": "doctor" ...