I'm having trouble setting a value for an object with a generic type

I am attempting to set a value for the property of an object with generic typing passed into a function. The structure of the object is not known beforehand, and the function receives the property name dynamically as a string argument. TypeScript is generating the error "Type 'string' cannot be used to index type 'T'."

My TypeScript code looks like this:

interface Value {
  [key: string]: any
}

interface SomeInterface<T> {
  key: string,
  value: T
}

function someFunction<T extends Value>({ key, value }: SomeInterface<T>) {
  value[key] = somevalue;
}

The line where I assign somevalue to the value triggers the error "Type 'string' cannot be used to index type 'T'", despite having created the index signature in the Value interface.

What could be the reason behind this issue?

Answer №1

An issue arises when you try to invoke someFunction with a more specific type of Value.

someFunction<{'specificKey': any}>(...);

As a result, the use of string as an index for value becomes invalid. Only specificKey can now serve as a valid index. To solve this, you can modify SomeInterface in a way that ensures it always contains a key suitable for indexing:

interface SomeInterface<T> {
  key: keyof T,
  value: T
}

See full example

Answer №2

When you define the generic type key for the specific object you're working with, it allows you to have clear types for both the key and its corresponding value.

interface Data {
  [id: string]: any
}

function assignValue<K extends keyof Data>({ id, content }: {id: K, content: Data[K]}) {
  content[id] = content;
}

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

Tabulate the number of items in an array based on the month and

I have received JSON data with dates indicating the creation time of multiple parcels. I want to analyze this data and calculate the total number of parcels created in each month. I am new to this process and unsure about which thread on Stack Overflow can ...

Submitting information to a server

I have a simple Angular 6 app with follow and unfollow buttons. When you click follow, the number increases. I want to save these follower numbers to a JSON server. Here is the link to the JSON server documentation: JSON Server Documentation To see a dem ...

Error encountered in Next.js: TypeScript error with code ts(7031) - The binding element 'Component' is implicitly assigned the 'any' type

Converting my NextJS project to TypeScript presented a challenge for me. When working on my _app.tsx file, I came across a type error: 'pageProps' implicitly has an 'any' type. ts(7031). The error message likely resembled this image: ht ...

How do I resolve validation function error messages in Vuetify?

When utilizing validation methods in Vuetify, I encountered the following error message↓ I simply want to create a form validation check and implement a function that triggers the validation when the 'submit' button is clicked. I believe my i ...

What can TypeScript do with high-level type functions?

Take a look at the following pseudo-code attempting to define a higher-order type function with a function-typed parameter M<?>: type HigherOrderTypeFn<T, M<?>> = T extends (...) ? M<T> : never; The syntax M<?> is not va ...

Converting JSON into Typescript class within an Angular application

As I work on my app using angular and typescript, everything is coming together smoothly except for one persistent issue. I have entity/model classes that I want to pass around in the app, with data sourced from JSON through $resource calls. Here's ...

I am looking for guidance on removing the bottom line from the ionic 4 segment indicator. Any advice or tips on

.segment-button-indicator { -ms-flex-item-align: end; align-self: flex-end; width: 100%; height: 2px; background-color: var(--indicator-color); opacity: 1; } I am a beginner in hybrid app development and ...

Typescript and RxJS: Resolving Incompatibility Issues

In my development setup, I work with two repositories known as web-common and A-frontend. Typically, I use npm link web-common from within A-frontend. Both repositories share various dependencies such as React, Typescript, Google Maps, MobX, etc. Up until ...

Retrieve the array from within the string

Any suggestions on how I can extract the array from this string? The current string is: "['Biller.Customer.Data@Taxonomy', 'Product.Platform and Enterprise Services Data.Data@Taxonomy']" I need to extract it to look like thi ...

Hiding a div after three clicks using HTML

What is the best way to hide a div tag containing an input tag after clicking on the input tag three times using HTML and angular? ...

Retrieve server information without utilizing data.map since array.map is not a supported function in next.js version 13

Currently, I am developing a list page using next.js 13 to display a collection of projects. I made an attempt to enable server-side rendering for this feature. The implementation is located in app/team/page.tsx import { useRouter } from 'next/navig ...

Encountering incorrect month while utilizing the new Date() object

My Objective: I am looking to instantiate a new Date object. Snippet of My Code: checkDates (currentRecSec: RecommendedSection){ var currActiveFrom = new Date(currentRecSec.activeFrom.year,currentRecSec.activeFrom.month,currentRecSec.activeFrom.day ...

Tips for retrieving data sent through Nextjs Api routing

Here is the API file I have created : import type { NextApiRequest, NextApiResponse } from 'next/types' import { PrismaClient } from '@prisma/client' const prisma = new PrismaClient() export default async function handler(req: NextApi ...

Determining the type of an overloaded method within a generic function

I am currently working on developing a versatile function that can subscribe to an event emitter. The function subscribe is designed to take 3 arguments: event name, event handler, and the event emitter to connect to. I am looking for ways to ensure accur ...

Transform the Standard class into a generic one in typescript

I've created a class that can take JSON objects and transform them into the desired class. Here's the code: import {plainToClass} from "class-transformer"; import UserDto from "../../auth/dto/user.dto"; class JsonConverter { ...

Creating a Loading Sign with a Button Component in React

Request Description: In my form, I have a button that triggers a submission to the backend. While the request is processing, I want the button to display a loading indicator instead of the usual text. Once the request is complete, I need the form to disap ...

Utilizing TypeScript with Vue3 to Pass a Pinia Store as a Prop

My current stack includes Typescript, Pinia, and Vue3. I have a MenuButton component that I want to be able to pass a Pinia store for managing the menu open state and related actions. There are multiple menus in the application, each using the same store f ...

What is the reason behind the error Generic indexed type in Typescript?

Here is a scenario where I have a specific generic type: type MapToFunctions<T> = { [K in keyof T]?: (x: T[K]) => void; }; It functions correctly in this instance: type T1 = { a: string }; const fnmap1: MapToFunctions<T1> = { a: (x: st ...

Challenges arise when incorporating interfaces within a class structure

I created two interfaces outside of a class and then proceeded to implement them. However, when I tried to assign them to private properties of the class, something went wrong and I'm unable to pinpoint the issue. Can anyone offer assistance with thi ...

The null error occurs when rendering with React's state array

When I try to call an API that emits JSON, I am encountering an issue. I call the promise API function in componentDidMount, set the state, and then call it in the render method, but it always returns a null error. I need assistance, please. Interface fo ...