Creating Object Types from Unions or Arrays in Typescript

One of the challenges I'm facing involves a function that takes an array of strings and generates an object with those strings as keys. Here's an example:

const obj = arrayToObject(['x', 'y', 'z']); // {x: any, y: any, z: any}

My goal is to have TypeScript dynamically assign types to the returned object based on the array provided in the function arguments. While I am aware that passing the array as a tuple can give me a union type of values, I'm unsure how to proceed from there. Is it even possible to achieve what I'm aiming for?

Answer №1

Are you satisfied with this solution:

const obj = arrayToObject(['a', 'b', 'c']);


type Convert<T extends ReadonlyArray<string>> = {
    [P in T[number]]: string

}
type Result = Convert<['foo', 'bar']> // {foo: string, bar: string)

function arrayToObject<T extends ReadonlyArray<string>>(args: readonly string[]): Convert<T> {
    return args.reduce((acc, elem) => ({...acc, [elem]: 'hello' }), {} as Convert<T>)
}

UPDATE

// It's important to remember that arrays are index-based data structures. Indexes have a `number` type

type Arr = readonly [1,2,3,4,5]

// Therefore, it is possible to access values by index
type Value1 = Arr[0] // 1
type Value2 = Arr[1] // 2 ... etc

type Value3 = Arr[0|1] // 1|2

// This demonstrates how distributive types function
type Value4 = Arr[number] // 5|1|2|3|4

// TypeScript recognizes that arrays use numbers as indexes, replacing `number` with allowed indexes. Although the actual workings of the TS compiler may be more complex, this is a simplified explanation.

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

A guide to verifying the type of response from an HTTP request in Typescript

Issue: I am currently working with Firebase cloud functions and encountering a specific problem. Let's consider the following function: function giveMeAnInteger(): number { return 123; } When calling this function like so: function call() { ...

The cucumber_report.json file will not update to reflect the most recent test steps

I have encountered an issue with the cucumber_reporter.json file not overwriting under the reports/html folder in my framework. To address this, I made changes to the cucumberOpts option within my config.ts file. By modifying the format setting to "json:./ ...

Updating the value of a specific property within an object in an array

I'm in the process of developing a stock trading application, and I have an empty array to store the stocks that are bought. Each time a stock is purchased, it adds an object to the array. If the same stock is bought again, I want to check for that sp ...

Angular 10 Compilation Error "NG8001 error: The element 'mat-card-title' is not recognized:

Recently, I encountered a compile error while trying to view my changes locally using the command 'ng serve'. The error is related to all of the imported modules in my components and displays messages like: 1. If 'mat-card-title' is an ...

Building a hierarchical tree structure using arrays and objects with Lodash Js

I am attempting to create a tree-like structure using Lodash for arrays and objects. I have two arrays, one for categories and the other for products, both with a common key. The goal is to organize them into a tree structure using string indexing. let ca ...

Using JavaScript, you can filter an array of objects based on a specific search input

I am in the process of implementing a filtering feature for a list using React, but surprisingly, I haven't been able to find any useful resources online to guide me through this common task. Currently, I have an array of users that I need to filter ...

Issues with loading NextJS/Ant-design styles and JS bundles are causing delays in the staging environment

Hey there lovely folks, I'm in need of assistance with my NextJS and Ant-design application. The current issue is only occurring on the stagging & production environment, I am unable to replicate it locally, even by running: npm run dev or npm r ...

Utilize PHP Sub-Arrays with Key References

Currently, I am experimenting with PHP 5.4 to handle data received from an HTTP API in XML format. To convert this XML data into an array, I utilize the following process: $xml = simplexml_load_string($resp); $json = json_encode($xml); $arr = json_decode( ...

Most effective method for storing large volumes of data within JavaScript objects

To uniquely identify each item, I need to store data using 3 keys. In this example, I am using i, j, z as the keys. console.time('global1'); var global1 = {}; for (var i = 0; i < 100; ++i) { for (var j = 0; j < 100; ++j) { for (va ...

The build process is encountering issues with lodash causing npm to fail

Utilizing Node: 16.20.2 Angular: CLI 11.2.5 Typescript: 4.1.5 @types/lodash: 4.14.177 An issue has arisen where the npm build process is failing with the following exception: Error: node modules/@types/lodash/common/object.d.ts:1026:46 error TS1 ...

Utilizing Angular for making API requests using double quotes

I am experiencing an issue with my service where the double quotation marks in my API URL are not displayed as they should be. Instead of displaying ".." around my values, it prints out like %22%27 when the API is called. How can I ensure that my ...

Returning an array to the main method

Consider the code snippet below with a main method: public static void main(String[] args) throws IOException{ int [] array = new int [1000]; int[] getArray=FileArrayProvider(array); for (int y = 0; y < getArray.length; ++y) { ...

showcasing JSON content on an HTML page using Angular version 4

I am dealing with JSON data that I can successfully read and access in the console. However, I am having trouble displaying this data on my HTML page. Every time I try to read it, I encounter an error message stating that it cannot read property of NewData ...

What is an improved method for defining a TypeScript type to store API method invocations?

Currently, I am exploring ways to enhance either GenericActionables or Items in a way that eliminates the need to manually add the API method name as a GenericActionables<"nameOfNewMethod"> to the Actionables type every time. Any suggesti ...

What causes the "Method Not Allowed" error while trying to restore the package.json package in VS2015?

When trying to restore a package.json file in VS2015, I am encountering a "Method Not Allowed" error. https://i.stack.imgur.com/OgK5P.png https://i.stack.imgur.com/AAkoQ.png The error log displays the following: npm ERR! Error: Method Not Allowed npm ER ...

PHP and MySQL return results in the form of arrays within arrays

I am currently working on a code snippet that generates a list of computers based on their respective manufacturers: <?php $query = " SELECT m.manufacturerName , c.id , c.computerName , GROUP_CONCAT(c.model SEPARATOR ',') clie ...

Using PHP to compare two arrays within a conditional statement

I have two arrays that I need to compare in PHP. My current IF statement performs two checks: It first checks if there are any rows retrieved from my database query. If the first check passes, I then need to iterate over the values in the first array and ...

Leveraging TypeScript with Ramda to efficiently propagate types

I have a small function called firstOrNull: import { propOr } from 'ramda' export const firstOrNull = propOr(null, '0') Now, I want to use this function with a property that returns QueryDocumentSnapshot<DocumentData>[] const or ...

Make sure to include a property that is indexed when typing

I am currently working on defining a type to represent a list (hash) of HTTP headers. This type is supposed to be a hash that only contains key / string pairs: type TStringStringHash = { [key: string]: string } However, the issue I am facing is that i ...

What is the most efficient way to move selected products to the payment page when the checkout button is clicked in React?

Need: I need to move all the selected products from the shopping cart to the payment page once the user clicks on the checkout button. List of products in the shopping cart: https://i.sstatic.net/31KpH.png The selected products should appear on the Payme ...