Create a Typescript index signature that incorporates individual generic types for each field

Many times, the keys of a record determine its value. For instance:

const record = {
   [2]: 5,
   ["string"]: "otherString",
   ["there is"]: "a pattern"
}

In these instances, each key of type K corresponds to the value K.
Here's a possible syntax for this concept (although not valid Typescript):

type DynamicIndex = {
    [key<T>: T]: T
}

So this would be valid:

const record: DynamicIndex = {
   [2]: 5,
   ["string"]: "otherString",
   ["there is"]: "a pattern"
}

But this wouldn't work:

const record: DynamicIndex = {
   [2]: "string",
   ["string"]: "otherString",
   ["there is"]: "a pattern"
}

Is there a way to achieve similar functionality? In my case, the value is Something<T> and not exactly T:

type ComplexCase<V> = {
    [key<K extends typeof V>: K]: Something<V[K]>
}

Answer №1

To achieve this, it is essential to utilize a particular function.
It is recommended to implement Type Validation in order to verify the legitimacy of the input value

type check<T, V> = T extends V ? T : V
type validateDynamicKey<T> = {
  [K in keyof T]: validateDynamicValue<K, T[K]>
}
type validateDynamicValue<K, V> = 
| K extends number ? number
: K extends string ? (
  K extends `${string} ${string}` ? Uppercase<V & string>
  : Lowercase<V & string>
)
: K

function validateDynamicKey<T>(data: check<T, validateDynamicKey<T>>) {
  return data;
}

validateDynamicKey({
  4: 4,
  'foo': 'bar',
  'baz baz': 'BAZ BAZ',

  5: 'asd', // Type 'string' is not assignable to type 'number'.(2322)
  asd: 'QWE', // Type '"QWE"' is not assignable to type '"qwe"'.(2322)
  'spa ced': 'foo' // Type '"foo"' is not assignable to type '"FOO"'.(2322)
})

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

Issue with NestedKeyof type arising from circularly referencing objects

Currently, I am in the process of constructing a library and my task involves implementing NestedKeyof. During my research, I came across the following code snippet: type NestedKeyOf<T extends object> = { [Key in keyof T & (string | number)]: ...

Obtain access to the child canvas element within the parent component

I'm currently working on an app that allows users to sign with a digital pointer. As part of the project, I have integrated react-canvas-signature. My next task is to capture the signature from the canvas and display it in a popup. According to thei ...

Build an Angular wrapper component for the phone textbox functionality

Looking to transform the Phone Mask solution below into an Angular component. Does anyone have a method to accomplish this? * Any solution that results in a similar component for a Phone textbox will suffice. Mask for an Input to allow phone numbers? ht ...

"Alert in Javascript executing prematurely prior to initiating the function for sending a get request

private validateURL(url: string) { let isValid = false; this.$http.get(url).then( (data) => { console.log('success'); isValid = true; } ).catch( (reason) => { console. ...

The attribute 'name' cannot be found within the class 'MyComponent'

I'm a beginner in Angular2 and I have no previous knowledge of version 1. Can you help me understand why this error is occurring and guide me on how to fix it? import { Component } from 'angular2/core'; @Component ({ selector: 'my- ...

I'm looking for a sample of RadPieChart for nativescript + angular. Can anyone help me out?

I'm currently working on a multi-platform application that requires a PieChart to be displayed on the main screen. Can someone point me to a comprehensive example of how to implement this? I have tried following this guide and modifying it according ...

The concept of passing arguments in Typescript

During my experience with Typescript programming, I encountered a situation like the one described below. If I pass an argument containing an object with the same name as the parameter defined in the function signature, Typescript recognizes it, but not ...

Display a semantic-ui-react popup in React utilizing Typescript, without the need for a button or anchor tag to trigger it

Is there a way to trigger a popup that displays "No Data Found" if the backend API returns no data? I've been trying to implement this feature without success. Any assistance would be greatly appreciated. I'm currently making a fetch call to retr ...

Resetting the timer of an observable in Angular 2

I have a unique service that automatically calls a method every 30 seconds. There is also a button that allows the user to reset the timer, preventing the method from being called for another 30 seconds. How can I make sure that the method does not get cal ...

Choosing a value type within an interface or object declaration

Is it possible to extract a nested type object from an interface or parent type? interface IFake { button: { height: { dense: number; standard: number; }; }; otherStuff: string; } type Button = Pick<IFake, 'button'& ...

Issue with reading the current length of an array object in a while loop in Angular 6

After successfully splitting an array into parts, I decided to add some filters to only include the items in the list that have an action status of (4). However, I encountered a problem where the while loop couldn't read the length of the array. This ...

Unlocking the accordion feature in Ionic 3 form: A step-by-step guide

I am currently working on a search form and want to incorporate it within an accordion so that users can simply click to expand the form. Below is the code snippet: TS. buildForm(): void { this.form = this.fb.group({ username: new FormControl(& ...

Invoke a function and assign it to an export variable

I have a query regarding a file containing an export constant that is utilized to construct a navigation bar in CoreUI. However, I am exploring methods to generate dynamic JSON data within other Components or the same file and then inject it into the exp ...

Pass an array of objects to an Angular 8 component for rendering

Recently, I started working with Angular 8 and faced an issue while trying to pass an array of objects to my component for displaying it in the UI. parent-component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: ...

Guide on deploying a web application using Socket.io and SvelteKit on Vercel

Currently, I'm developing a multiplayer .io-style game that utilizes both Socket.io and SvelteKit. While testing the project on a local development server, everything runs smoothly. However, upon deploying to Vercel, an error message stating Failed to ...

"Trouble with Typescript's 'keyof' not recognizing 'any' as a constraint

These are the current definitions I have on hand: interface Action<T extends string, P> { type: T; payload: P; } type ActionDefinitions = { setNumber: number; setString: string; } type ActionCreator<A extends keyof ActionDefinitions> ...

Ways to merge two arrays into one in React JS

Here are two arrays presented below: const arrayA = { 0: { id: XXXXXXX, name: "test" }, 1: { id: YYYYYYY, name: "example" } } const arrayB = { 0: { id: XXXXXXX, category: "sea", } 1: { id: YYYYY ...

`Incorporate concurrent network requests in React for improved performance`

I am looking to fetch time-series data from a rest service, and currently my implementation looks like this async function getTimeSeriesQuery(i) { // Demonstrating the usage of gql appollo.query(getChunkQueryOptions(i)) } var promises = [] for(var i ...

What is the best way to access JavaScript built-ins in Typings when faced with name conflicts?

I am currently in the process of updating the Paper.js Typings located on GitHub at this repository: github.com/clark-stevenson/paper.d.ts Within Paper.js, there exists a MouseEvent class, which is not an extension of JavaScript's MouseEvent, but ra ...

Setting a value in Ionic 3 HTML template

Attempting to assign a value in an Ionic 3 template from the ts file while also adding css properties but encountered an issue. PROBLEM Error: Uncaught (in promise): Error: No value accessor for form control with name: 'image' Error: No va ...