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

Receiving 'Module not found' error in Typings on specific machines within the same project. Any suggestions on how to troubleshoot this issue?

I have a project cloned on two separate machines, each running VS2015 with Typings 1.8.6 installed. One machine is running the Enterprise version while the other has the Professional version, although I don't think that should make a difference. Inte ...

Tips for adjusting the zIndex of the temporary drawer component in TypeScript

Currently, I am working on incorporating a "temporary" drawer that is clipped under the app bar. Please note that the drawer variant is set to 'temporary' and it needs to be clipped under the app bar. If you need more information, refer to my pr ...

How can I populate a mat-table in Angular 7 with data stored in an object?

At the moment, my code is set up to populate a table with data. In my component.ts file: import { HttpClient } from "@angular/common/http"; import { Component, OnInit } from "@angular/core"; import { FormBuilder, FormGroup, Validators } from "@angular/fo ...

Enhancing TypeScript Modules

Recently, I encountered an issue with my observable extension. Everything was functioning perfectly until I updated to angular 6 and typescript 2.7.2. import { Observable } from 'rxjs/Observable'; import { BaseComponent } from './base-compo ...

What is the best way to mock imports in NestJS testing?

I am interested in writing a unit test for my nestjs 'Course' repository service, which has dependencies on Mongoose Model and Redis. courses.repository.ts: import { Injectable, HttpException, NotFoundException } from "@nestjs/common"; ...

Is there a way to update the data on a view in Angular 9 without the need to manually refresh the page?

Currently, I am storing information in the SessionStorage and attempting to display it in my view. However, there seems to be a timing issue where the HTML rendering happens faster than the asynchronous storage saving process. To better illustrate this com ...

The initial character of the input must always be a letter

I need assistance with an input element that requires 5 characters, with the first character being a letter: <input mdInput #acronyme placeholder="Company" type="text" maxlength="5" minlength="5" required [value]="acronyme.value.toUpperCase()"> Th ...

Challenging Issue: "The 'any' type cannot be assigned to the 'never' type"

Currently facing a challenging Typescript problem that has me puzzled. The issue arises at the line themeToChange[tileId][key] = value; The error message states Type 'any' is not assignable to type 'never' This error is directly rela ...

Typing a general d3 selection to target various types of SVG elements

I am looking for a callback function that can be utilized with both rect and circle elements. Here is an example: function commonTasks(selection:d3.Selection<PLACEHOLDER_TYPE, MyDataType, SVGGElement, unknown>) { selection .classed('my-c ...

"Utilizing aws-sdk in a TSX file within a React project: a step-by

When working on a project using TypeScript (tsx) for React, I encountered an issue with uploading images to the server using aws-sdk to communicate with Amazon S3. To resolve this, I made sure to install aws-sdk via npm and typings. UploadFile.tsx import ...

Access information from a different component within the route hierarchy

Suppose you have three components named A, B, and C with the following routing direction: A -> B -> C To retrieve data from the previous component (going from C to get data from B), you can use the following lines of code: In Component C: private ...

Generating data types based on the output of functions

I'm currently working on optimizing my typescript react code by reducing repetition. I'm curious to know if there's a way to generate a type based on the return type of a known function? For example: const mapStateToProps = (state: StoreSt ...

What are the steps to resolve TypeScript errors in OpenLayers version 6.6.1?

Since updating to OpenLayers 6.6.1, I have been bombarded with numerous typescript errors related to generics. For example... import olLayerVector from 'ol/layer/Vector'; import olFeature from 'ol/Feature'; public static highlightOver ...

Having trouble resolving errors in Visual Studio Code after failing to properly close a parent function? Learn how to fix this issue

Here we have the code starting with the construct function followed by the parents function public construct() //child { super.construct; } protected construct() //parent { } The issue arises where I am not receiving an er ...

Guidance on showcasing the current day's weekday name through TypeScript

I am perplexed about how to begin in TypeScript after successfully setting up the display using gate. ...

Issue: Unable to resolve all parameters for LoginComponent while implementing Nebular OAuth2Description: An error has occurred when attempting to

I have been attempting to utilize nebular oauth in my login component, following the documentation closely. The only difference is that I am extending the nebular login component. However, when implementing this code, I encounter an error. export class Lo ...

Jest mock module request causing a timeout issue

I am encountering an issue with the code snippet below in my application request.ts import request from 'request' export const funcA = async ( apiToken: string, body: any): Promise<any> => { return new Promise((resolve, reject) =&g ...

Exploring the versatility of Vue.js through props and scoped slots

Coming from a React background, I am used to being able to easily alter children components before they render. However, after spending hours reading the VueJS documentation and searching forums, I have not been able to find a straightforward way to do thi ...

Having trouble resolving modules with Angular 2 and ASP.NET 5 (unable to locate angular2/core)?

I am diving into a fresh ASP.NET5/MVC6 project and facing some challenges along the way. Struggle 1 When I opt for classic as the moduleResolution in my tsconfig.json, I encounter an error stating: Cannot locate module 'angular2/core' Strugg ...

Receiving an eslint error while trying to integrate Stripe pricing table into a React web application

If you're looking to incorporate a Stripe documentation code snippet for adding a stripe-pricing-table element, here's what they suggest: import * as React from 'react'; // If you're using TypeScript, don't forget to include ...