Tips for using a string as a generic type in TypeScript

Looking to create a flexible type that can transform existing types into ones that align with a specific API response structure. My goal is to take a variety of types and generate new types based on them, constructed as follows:

// original type definition
interface IModel {
  key1: string
  key2: string
}

// desired inferred type
interface IModelResponse {
  model: {
    key1: string
    key2: string
  }
}

// seeking to achieve this using TypeScript generics
// example implementation:
type IModelResponse = IBaseResponse<IModel, 'model'>

My attempt so far has been:

export interface IBaseResponse<T, modelName extends string> {
  [key: modelName]: T
}

However, I encountered the error message "An index signature parameter type must be either 'string' or 'number'." Am I missing something here, or is it not feasible to implement this as intended? Any assistance would be greatly appreciated!

Answer №1

This technique can be applied by using the in keyword

interface IData {
  id: number
  name: string
}

type ResponseData<T, DataType extends string> = {
  [prop in DataType]: T
}

type IDataResponse = ResponseData<IData, 'data'>

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

Find out how many shared element locators exist in Selenium

I am attempting to dynamically select an element using a for loop. To determine the range, I require knowledge of the element count - how can this be achieved in selenium (python)? Is it necessary to run a JavaScript script for this purpose? # How do I ...

How can you pass arguments between commands in discord.js?

I need to transfer arguments; I have attempted to make them global variables, but I am unsure about the correct approach. Command using the arguments : let messageArray = message.content.split(" "); const args = messageArray.slice(1); const invi ...

How to Ensure that the Hidden Value of Select Statement in Angular is Always Displayed as Text

Is there a way to customize the top part of a dropdown menu so that it always displays a specific phrase, like 'Symbols' in this case, regardless of the option selected? Currently, the top part shows the last selected symbol, but I want it to be ...

Sending a Variable and List to a Controller using Ajax

I am having an issue with passing data from a Text Box and a Select Options Multiple using knockout selectedOptions in a viewModel to my Controller via ajax. I am unable to receive the MetricsChosenModel information. var MetricsChosenModel= wi ...

I am attempting to set up React, but I keep encountering an issue that says 'Error: EPERM: operation not allowed'

My attempts to set up React have been unsuccessful so far. Initially, I tried installing it using the command npx create-react-app ./, which did not work. Then, I attempted to run npm init react-app my-app, but unfortunately, that also failed. The error me ...

Change button text with JS on click

My goal is to update the text on a button click, changing it from 'Copy' to 'Copied!' as part of a custom clipboard implementation. The code I'm currently using is as follows: HTML: <button id="copyButton2">Copy</button& ...

Utilize the key as the value for options within an object iteration in Vue.js

I have an object called colors, which stores color names: { "RD": "Red", "BL": "Blue", "GR": "Green", "YW": "Yellow" } In my dropdown menu, I'm generating options for each color in the colors object: <select v-model="colors"> <op ...

Utilizing object as props in ReactJS with TypeScript

I'm new to working with ReactJS, and I made the decision to use typescript for my current project. The project is an application that fetches movies from an API and displays them. Take a look at the app: import React from 'react'; import &a ...

Having trouble adding custom props to MUI-Material ListItemButtonProps? Facing a TypeScript error?

This particular task should be relatively straightforward. I am seeking a custom component that inherits all props from ListItemButtonProps, while also adding an extra state prop: type SidebarListItemButtonProps = ListItemButtonProps & { state: Sideb ...

I'm experiencing an issue where my express-session is being reset with every new request, leading me to question if this is related to the development environment I am using (REACT + EXPRESS)

UPDATE - I have ruled out a development environment issue as the same problem persists in production. Thank you for taking the time to look into this. I've searched through numerous questions and attempted various solutions with no success. To give ...

Unlock the Secrets of JavaScript Key Codes

I am currently dealing with a JavaScript routine that I did not create. This routine is triggered by the onkeydown attribute of a text box in order to restrict certain keystrokes. The first argument does not seem to have any significance. The second argum ...

What is the process for converting primitive values in the expressions `1 + {}` and `{} + 1`?

Being a novice developer, I am struggling to comprehend why the following statements result in different outputs. Could someone please explain why JavaScript interprets these two expressions differently and produces distinct outcomes? 1 + {} // => "1[o ...

Testing the unit with a customized header in the interceptor

I've been struggling to execute a unit test within an Angular 6 interceptor, but despite numerous attempts, I keep encountering the following error: Error: Expected one matching request for criteria "Match by function: ", found none. I'm rela ...

What is the best way to rearrange elements within an object when there is no predetermined starting order?

Someone assisted me in refining this code snippet import React, { useEffect, useState } from "react"; import _ from "lodash"; // const SeleccionClientes = ""; const items = [ { client: "Microsoft", idClient: 0, idProjectType: 1, project ...

Certain URLs are known to prevent the callback function from executing in the axios nuxt module

I have implemented two buttons, "Confirm" and "Delete", on my nuxt.js page. Clicking each button triggers the confirm() and delete() functions respectively. Although the code for these functions is almost identical, the URLs they use are different. Interes ...

Populate an ASP Form using Javascript in Android Studio

Being relatively new to Android studio, I have been experimenting with various methods but now need some assistance. I am looking to input data into an ASP.NET Website-form using Android studio. The traditional JavaScript approach does not seem to be effec ...

Removing a dynamic element from a Bootstrap Table after sorting the data

Encountering an issue with wenzhixin's Bootstrap Table. Within one of the table cells, there is a button that, when pressed, gets deleted and replaced with a new button featuring a popover dynamically. The problem arises when sorting the table - the ...

Utilize jQuery to dynamically apply Bootstrap classes while scrolling through a webpage

Having an issue with jQuery. Trying to include the fixed-top class (Bootstrap 4) when scrolling, but it's not working as expected. jQuery(document).ready(function($){ var scroll = $(window).scrollTop(); if (scroll >= 500) { $(".robig").a ...

Enjoy the convenience of accessing your QR code result with just a click on the link provided

Stumbled upon this code snippet on . It allows scanning QR codes and displaying the results as plain text. However, I wanted the result to be a clickable link, like www.google.com/(qrcodescanresult). <script src="html5-qrcode.min.js">< ...

Submitting forms with Ajax using Jquery

I'm looking to utilize ajax to submit a form in the background. My attempt so far is as follows: <div class="form-horizontal" id="form"> <label for="name" class="control-label">Enter your name</label> <div class="controls ...