typescript Object that consists of properties from an array with a defined data type

I have an array consisting of strings. I am trying to transform this array into an object where each string is a property with specific attributes assigned to them.

export interface SomeNumbers {
  name: string;
  value: number;
}
const arr = ['apple', 'banana', 'cherry'];

const fruitsObject = {}; // How can I define a type for this object?

arr.forEach((fruit, index) => {
  fruitsObject[fruit] = {
    name: fruit,
    value: index
  };
});

Answer №1

Here is an example that may suit your needs:

    export interface SetOfNumbers {
      title: string;
      data: number;
    }

    const elements = ['one', 'two', 'three'];

    const mapping: { [identifier: string]: SetOfNumbers }  = {};

    elements.forEach((value, index) => {
      mapping[value] = {
        title: value,
        data: index
      };
    });

Answer №2

Utilizing the reducer pattern can effectively handle both type and runtime scopes.

export interface SomeNumbers<N, V> {
    name: N;
    value: V;
}

type Reducer<
    Tuple extends Array<any>,
    Acc extends Record<string, any> = {},
    Index extends number[] = []
    > =
    Tuple extends []
    ? Acc
    : (Tuple extends [infer Head, ...infer Tail]
        ? (Head extends PropertyKey
            ? Reducer<
                Tail,
                Acc & Record<Head, SomeNumbers<Head, Index['length']>>,
                [...Index, 1]
            >
            : never)
        : never)



const generator = <Tuple extends string[]>(tuple: [...Tuple]) =>
    tuple.reduce((acc, elem, index) => ({
        ...acc,
        [elem]: {
            name: elem,
            value: index
        }
    }), {} as Reducer<Tuple>)

const output = generator(['first', 'second', 'third'])

//  {
//     name: "first";
//     value: 0;
}
output.first 

Interactive Demo

Reducer type performs a similar function to the generator function. However, Reducer recursively iterates through the tuple.

Reducer - recursively traverses the Tuple and merges Acc with SomeNumbers<N,V>. Index - serves as an additional tuple for indexing. The value in Index increases by 1 element each iteration, corresponding to the index of the currently processed element

For more examples, check out my blog

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

Working with TypeScript: Overriding a Parent Constructor

I am new to TypeScript and currently learning about Classes. I have a question regarding extending parent classes: When we use the extends keyword to inherit from a parent class, we are required to call the super() method in the child class constructor. H ...

What is the best way to iterate through a collection of two or more arrays in order to determine the total length of all

https://i.stack.imgur.com/PpFlB.pngI currently have multiple Arrays containing various inputs this.listNumber = [ { "GenericQuestions": [ { "input": "long", }, { "input": & ...

Creating a completely dynamic button in Angular 6: A step-by-step guide

I have been working on creating dynamic components for my application, allowing them to be reusable in different parts of the program. At this point, I have successfully developed text inputs that can be dynamically added and customized using the component ...

Clear pagination - results generated by the clr-dg-page-size component

I'm currently developing an Angular 8 application using Clarity UI. Within my app, I have implemented a datagrid with pagination. My challenge lies in fetching data after changing the number of items per page, as there is no output provided by the Cl ...

Maximize the benefits of using React with Typescript by utilizing assignable type for RefObject

I am currently working with React, Typescript, and Material UI. My goal is to pass a ref as a prop. Within WidgetDialog, I have the following: export interface WidgetDialogProps { .... ref?: React.RefObject<HTMLDivElement>; } .... <div d ...

Do Angular 2 component getters get reevaluated with each update?

What advantages do getters offer compared to attributes initialized using ngOnInit? ...

The API functions seamlessly with TypeScript, however, during the transpilation process, it fails to locate the model

I am in the process of developing a straightforward API that is capable of Creating, Reading, and Deleting student information within a postgres database. Interestingly, I have encountered an issue when using ts-node-dev without transpiling the files to J ...

Changing the type of an object's property in TypeScript on the fly

I am working on a TypeScript function that is designed to dynamically modify the property of an object. Here is the function: const updateProperty = (value: any, key: keyof Type1, obj: Type1) => { obj[key] = value; } Below is the definition of "Typ ...

Does the message "The reference 'gridOptions' denotes a private component member in Angular" signify that I may not be adhering to recommended coding standards?

Utilizing ag-grid as a framework for grid development is my current approach. I have gone through a straightforward tutorial and here is the code I have so far: typography.component.html https://i.stack.imgur.com/XKjfY.png typography.component.ts i ...

Creating a unique Angular 2 Custom Pipe tutorial

I've come across various instances of NG2 pipes online and decided to create one myself recently: @Pipe({name: 'planDatePipe'}) export class PlanDatePipe implements PipeTransform { transform(value: string): string { return sessionStor ...

Angular 2: Shared functions for universal component usage

I am working on an Angular 2 webpack project and I have come across a scenario where I have some functions that are repeated in multiple components. I want to find a way to centralize these functions in a "master" class or component so that they can be eas ...

Is there a way to change the data type of all parameters in a function to a specific type?

I recently created a clamp function to restrict values within a specified range. (I'm sure most of you are familiar with what a clamp function does) Here is the function I came up with (using TS) function clamp(value: number, min: number, max: number ...

The `note` binding element is assumed to have an unspecified `any` type

I'm encountering an error that I believe is related to TypeScript. The issue arises when trying to work with the following example. I am using a JavaScript server to import some notes. In the NoteCard.tsx file, there is a red line under the {note} cau ...

Implement Php gettext functionality in Typescript

I have a keen interest in AngularJs 2, and I am planning to incorporate it into my upcoming project. I would like to integrate i18n with Php gettext. In a previous project, I utilized Php gettext by embedding Php within Javascript code as shown below: // ...

What is the best way to retrieve data from MySQL for the current month using JavaScript?

I need to retrieve only the records from the current month within a table. Here is the code snippet: let startDate = req.body.startDate let endDate = req.body.endDate let result = await caseRegistration.findByDate({ p ...

Ensuring that files adhere to the required format, whether they be images

Three separate input fields are being used, each with its own name for identification. A validation method is called to ensure that the files selected in these input fields are not duplicates and that they are either images or PDFs but not both. While thi ...

Steps for incorporating a type declaration for an array of objects in a React application with TypeScript

How can I specify the type for an array of objects in React using TypeScript? Here is the code snippet: const SomeComponent = (item: string, children: any) => { //some logic } In this code, you can see that I am currently using 'any' as ...

DeActivation only occurs once per route

Having an issue with the CanDeActivate() function in Angular2. The problem arises when a user tries to leave a page while in edit mode, triggering a popup with Yes, No, and Cancel options. If the user clicks on Cancel, the popup closes. If they click on No ...

Storing Buffer data in Postgres bytea using TypeORM is limited to only 10 bytes

I am encountering an issue while trying to store images in a postgres database, as only 10 bytes of data are being saved. Here is the sequence of events: Initially, I receive a base64 encoded string on my server. I then convert it into a Buffer, assign i ...

Modify every audio mixer for Windows

Currently working on developing software for Windows using typescript. Looking to modify the audio being played on Windows by utilizing the mixer for individual applications similar to the built-in Windows audio mixer. Came across a plugin called win-audi ...