Creating dynamic key objects in TypeScript with index signatures: A beginner's guide

How can the code be optimized to automatically initialize a new product type without adding extra lines of code? Failure to initialize the variable results in a syntax error.

enum ProductType {
   PC = 'pc',
   LAPTOP = 'laptop',
   TV = 'tv'
}

let productList: { [key in ProductType]: Product[] | undefined } = {
  [ProductType.PC]: undefined,
  [ProductType.LAPTOP]: undefined,
  [ProductType.TV]: undefined
}

Answer №1

If I have understood correctly, you are looking to avoid adding a new line for each new ProductType in the initialization object. One solution is to make it more dynamic by reducing over the keys of the enum into an object.

enum ProductType {
  PC = 'pc',
  Laptop = 'laptop',
}

const newObj = Object.values(ProductType).reduce(
   (accumulator, key) => ({
      ...accumulator,
      [key]: undefined,
   }),
   {} as Record<ProductType, undefined>
);

// const newObj = { pc: undefined, laptop: undefined };

Answer №2

Following VLAZ's advice, I implemented the code like this:

const productCatalog: { [key in TypeOfProduct]?: CatalogedProduct[] | undefined } = {}

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

When using Next.js and Jest, an error may occur stating "Element type is invalid: expected a string or a class/function but got an object."

I am currently in the process of setting up unit tests for my Next.js project. I have carefully followed the guidelines provided in the official documentation on testing. The issue I'm encountering appears to be related to either the configuration it ...

Having trouble declaring custom pipes in Angular

A new pipe named 'shortend.pipe.ts' has been created within the app folder. import { PipeTransform } from "@angular/core"; export class ShortendPipe implements PipeTransform { transform(value: any, ...args: any[]) { return ...

Translate Firestore value updates into a TypeScript object

Here are the interfaces I'm working with: interface Item { data: string } interface Test { item: Item url: string } In Firestore, my data is stored in the following format: Collection Tests id: { item: { data: " ...

How can I silence the warnings about "defaultProps will be removed"?

I currently have a next.js codebase that is experiencing various bugs that require attention. The console is currently displaying the following warnings: Warning: ArrowLeftInline: Support for defaultProps will be removed from function components in a futur ...

Is there a method to run code in the parent class right after the child constructor is called in two ES6 Parent-Child classes?

For instance: class Parent { constructor() {} } class Child { constructor() { super(); someChildCode(); } } I need to run some additional code after the execution of someChildCode(). Although I could insert it directly there, the requirement is not to ...

encountered an issue when testing a dynamic route in Next.js with postman

I recently created a new API route named route.ts, where I included two different routes. One route retrieves all users from the database, while the other retrieves a specific user based on their ID passed as a query parameter. However, when testing these ...

Tips for selecting specific types from a list using generic types in TypeScript

Can anyone assist me in creating a function that retrieves all instances of a specified type from a list of candidates, each of which is derived from a shared parent class? For example, I attempted the following code: class A { p ...

When attempting to retrieve information from the API, an error occurred stating that property 'subscribe' is not found in type 'void'

I've attempted to use this code for fetching data from an API. Below is the content of my product.service.ts file: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { map, Observ ...

The new mui v5 Dialog is having trouble accepting custom styled widths

I am facing an issue with my MUI v5 dialog where I cannot seem to set its width using the style() component. import { Dialog, DialogContent, DialogTitle, Paper, Typography, } from "@mui/material"; import { Close } from "@mui/icons- ...

AmCharts stacked bar chart - dynamically adjust value visibility (adjust transparency) based on user interaction

I recently utilized amcharts to construct a bar chart. The creation of my stacked bar chart was inspired by this specific example. Currently, I am attempting to modify the alpha (or color) of a box when hovering over another element on my webpage, such as ...

Issue arises when trying to implement sidebar navigation in Angular with Materialize CSS

Just starting my Angular journey and running into some trouble trying to set up a practical and responsive menu using SidebarNav and Dropdown. I used CLI to install and configure angular2-materialize and materialize-css. To create the menu, I made a comp ...

Creating Dynamic Ionic Slides with Additional Slides Inserted Before and After

Hello, I am currently using ngFor to generate a set of 3 slides with the intention of starting in the middle so that I can smoothly slide left or right from the beginning. When I slide to the right, I can easily detect when the end is reached and add anot ...

Converting axios response containing an array of arrays into a TypeScript interface

When working with an API, I encountered a response in the following format: [ [ 1636765200000, 254.46, 248.07, 254.78, 248.05, 2074.9316693 ], [ 1636761600000, 251.14, 254.29, 255.73, 251.14, 5965.53873045 ], [ 1636758000000, 251.25, 251.15, 252.97, ...

Establishing a Next.js API endpoint at the root level

I have a webpage located at URL root, which has been developed using React. Now, I am looking to create an API endpoint on the root as well. `http://localhost:3000/` > directs to the React page `http://localhost:3000/foo` > leads to the Next API end ...

Improve your code quality with TypeScript's type checking capabilities

I am currently utilizing TypeScript version 1.4.1 and I have a need to import an external module (specifically "chai") while ensuring type checking compatibility. Yet, I seem to be facing a naming conflict issue with the following code snippet: /// <r ...

Uh oh, it looks like there's an issue! The function getCoordinates is not recognized for this.locations

Whenever I attempt to execute the method in my class (getCoordinates()), an Error is thrown: ERROR TypeError: this.locations[0].getCoordinates is not a function What am I doing wrong? The service method I'm using: getLocations(){ return this ...

Is it not possible to call this authentication expression in a Typescript file when using Next JS?

I am currently developing a sign-in method for my Next.js application and I have been referring to the GitHub repository's recommended documentation. However, upon reaching the authentication folder step, I encountered an error regarding the sign-in ...

Unable to expand the dropdown button collection due to the btn-group being open

Having trouble with the .open not working in Bootstrap 4.3 after adding the btn-group class to open the dropdown... I am looking for a way to load the dropdown without using JavaScript from Bootstrap. This is the directive I am trying to use: @Host ...

When the query result is received in Angular TypeScript, translate epoch time into a time string

Here is the dilemma I am currently facing: I have an Angular script that requests data from a backend service and receives query results to display to the user. One of the fields in the query response is a time stamp, which is currently in epoch time forma ...

What is the best way to parse JSON data with Typescript?

I am dealing with JSON data structured as follows: jsonList= [ {name:'chennai', code:'maa'} {name:'delhi', code:'del'} .... .... .... {name:'salem', code:'che'} {name:'bengaluru' ...