Can we create a generic mapped object type using TypeScript?

I have two sets of TypeScript definitions that are similar:

enum OperationType1 {
  start = 'start',
  stop = 'stop'
}
type ConfigForOperationType1 = { [key in OperationType1]: TestConfig };

enum OperationType2 {
  play = 'play',
  pause = 'pause'
}
type ConfigForOperationType2 = { [key in OperationType2]: TestConfig };

I can use them as shown below:

const config1: ConfigForOperationType1 = {
  [OperationType1.start]: { ... },
  [OperationType1.stop]: { ... }
};

const config2: ConfigForOperationType2 = {
  [OperationType2.play]: { ... },
  [OperationType2.pause]: { ... }
};

Now, I want to replace ConfigForOperationType1 and ConfigForOperationType2 with a single generic type called OperationConfig, taking Operation as a parameter like this:

type GenericOperationConfig<T> = { [key in T]: TestConfig };

const config1: GenericOperationConfig<OperationType1> = { ... };
const config2: GenericOperationConfig<OperationType2> = { ... };

The code above is causing an error and throws the following exception:

TS2322: Type 'T' is not assignable to type 'string | number |
symbol'. Type 'T' is not assignable to type 'symbol'.

The question. How can I make the mapped object type (GenericOperationConfig) accept parameters? Or is there another convenient alternative?

Answer №1

Yes, it is feasible to achieve this, but only under the condition that the type parameter T is capable of being a property key. Therefore, specifying an upper bound of PropertyKey for T allows for this functionality.

type ConfigGeneric<T extends PropertyKey> = {
    [item in T]: ConfigurationData
};

const settings1: ConfigGeneric<Setting1> = { ... };

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

Transform a dynamic set of distinct types into a different set of distinct types through mapping

If we consider the type union below: type Entity = Circle | Square; interface Circle { type: "circle"; radius: number; } interface Square { type: "square"; sideLength: number; } Is there a way to dynamically convert t ...

Tips for maintaining a marker at the bottom of the screen while zooming, similar to Google Maps

Is there a way to customize the zoom behavior in my project? I want to maintain the bottom position while resizing the other three directions, and also include pitch adjustments. https://i.sstatic.net/hQdg8.gif https://i.sstatic.net/m3xef.gif I aim for t ...

"Observables in RxJs: Climbing the Stairs of

Previously, I utilized Promise with async/await syntax in my Typescript code like this: const fooData = await AsyncFooData(); const barData = await AsyncBarData(); ... perform actions using fooData and barData However, when using RxJs Observable<T> ...

Tips for keeping your attention on the latest HTML element

Welcome to my HTML Template. <div cdkDropList class="document-columns__list list" (cdkDropListDropped)="dragDrop($event)" > <div cdkDrag class="list__box" ...

Tips for filtering data using an array within an object containing arrays

Below is the provided information: userRoom = ['rm1']; data = [{ name: 'building 1', building: [{ room: 'rm1', name: 'Room 1' },{ room: 'rm2', name: ' ...

Type narrowing is ineffective for discriminated unions in most cases

Consider the type definition provided below: type A = { a: string } | { a?: undefined; b: string } This essentially means that if you include a, it should be the only property provided. If you do not include or have a as undefined, then you also need to p ...

What is the process for creating static pages that can access local data within a NextJS 13 application?

I recently completed a blog tutorial and I must say, it works like a charm. It's able to generate dynamic pages from .md blog posts stored locally, creating a beautiful output. However, I've hit a roadblock while attempting what seems like a sim ...

Tips for accessing child elements within an Angular component

I'm struggling to get a reference of child elements within a component. I have experimented with ElementRef, TemplateRef, QueryList, ViewChild, ViewChildren, ContentChild, and ContentChildren without success. <app-modal> <section #referenc ...

Interactive MUI React Tab Components

Currently, I am working with MUI tabs and have added an X button to them. However, I am facing difficulties in making the tabs closeable. I would greatly appreciate any help or guidance on how to achieve this feature. Despite trying different methods, I ha ...

Filter an item from an array of objects using its index (TypeScript and Next.js)

I am attempting to filter out a specific item from the list by using its index. For example, if I want to remove the item with index 0, I would pass the number 0 to the filter function in order to return all objects except for the one at position 0. Belo ...

Tips for implementing pagination on a large JSON file without traditional pagination controls

Looking for the best way to implement pagination in a NextJs app that loads products from a local JSON file? This JSON file doesn't have any page properties, so the only option is to limit the number of products shown by using slice: {Object ...

Receiving an error while passing properties to a React component: "Property 'firstName' is not found on type 'Readonly<{}>'."

As a beginner in React, I need some patience I'm attempting to create a simple component where users can input their first and last names, update the values, and see them displayed after clicking a button. However, I keep encountering TypeScript comp ...

What is the best way to retrieve the dimensions of an Angular 5 Component prior to displaying it on the screen?

I am currently working on integrating a generic tooltip feature in Angular 5. In order to ensure proper positioning, especially centering relative to the target element, I need to obtain the width and height of the tooltip before it is rendered. While I h ...

Exploring the seamless integration of Worldpay with Angular 2

I am in the process of incorporating Worldpay into my angular2 application. Utilizing the own form (own-form) approach, it is essential to include their script on the page: <script src="https://cdn.worldpay.com/v1/worldpay.js"></script> Addin ...

Can Next.js accommodate server-side redirection with internationalization?

I'm working on a small Next.js app that has pages accessible only to logged in users. To manage the authenticated routes, I created an HOC (withAuth) that handles redirection on the server side to prevent page flashing on the client side. Everything i ...

React's Redux persist is causing a duplication of requests being sent

I am currently utilizing redux-persist along with Redux Toolkit. I have observed a peculiar behavior where, upon changing the slice (RTK), a request is sent to the server. When using redux-persist without a persister, only one request is made as expected. ...

Invalid file name detected during the download process

Below is the Javascript code I currently use to download a pdf: var link = document.createElement('a'); link.innerHTML = 'Download PDF file'; link.download = "Report.pdf"; link.href = 'data:application/octet-stream;base64 ...

Ways to integrate npm dependencies into your Cordova plugin

Currently working on implementing a Cordova plugin called core-cordova found in this repository. This particular plugin has a dependency on another NPM package. The issue arises after installing the plugin in my app using: $ cordova plugin add @aerogears ...

Why is it that the resource fails to load in an Angular localhost environment when making an http request?

In the realm of ASP.NET MVC projects lies my creation, a masterpiece utilizing Angular UI components powered by ASP.NET WebAPI. As an explorer navigating the unknown territory of Angular, I present to you the sacred texts residing within my project. Behol ...

Troubleshooting Type Error in React with Typescript: Finding Solutions for HTMLButtonElement Issue

Hey there! I recently created a TodoList Sample using React, Redux, Typescript, and SCSS. However, I encountered an issue with Typescript error which states the following: Error Status: Type '(event: { target: HTMLButtonElement; }) => void' ...