How to retrieve the type of a computed keyof T as a generic type within TypeScript

I am working with two different interfaces:

interface PersonRequirements{
    user:string,
    password:string,
    id:number
}
export interface Requirement<R> {
    name: keyof R & string,
    save: () => any,/* I want this return type to be same as return type of founded key in R*/
}

Here is an example of how I am using them:

const idRequirement:Requirement<PersonRequirements>={
    name:"id",
    save:function ():number/* I want this return type to be same as id's return type(number) but in a generic type safe way*/{
        //
    }
}

I am looking for a way to ensure that the save() method returns the same data type as the 'id' property, while maintaining type safety. How can I achieve this?

Answer №1

To enforce the property name at compile time, you can introduce another generic parameter.

export interface Rule<R, N extends keyof R & string> {
    key: N; // ensures that the key matches the provided property name
    apply(): R[N];
}

Here's an example of how you can use it:

const ageRule: Rule<PersonRules, "age"> ={
    key: "age",
    apply: () => 18
}

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

Creating dynamic layouts using Handlebars.js recursion

I'm working with a basic object hierarchy that includes: Category String name List childCategories; My goal is to use handlebars to represent this structure in a generic manner, but I'm struggling on how to nest layouts. Here's the curre ...

Activating gzip compression using fetch.js

I am utilizing fetch.js (https://github.com/github/fetch) to transmit a rather substantial JSON object to the backend. The size of the JSON is significant due to it containing an SVG image string. My question is whether fetch.js applies gzip compression a ...

Is it possible for jQuery to create a popup window displaying a specific value?

Using JavaScript, I have implemented functionality to open a child window when the user clicks on a button from the parent window. The child window contains a textbox and a button. When the user clicks on the button in the child window, I want to retrieve ...

Step-by-step guide to launching a new window or tab without automatically bringing it into focus

Is it possible to use JavaScript to open a URL in a new tab without giving that tab focus on a click event? ...

Making a POST request to a Next.js API route results in a 500 Internal Server Error being sent back

Check out the code in createComment.ts file, which serves as a Next.js api route: import type { NextApiRequest, NextApiResponse } from 'next' import sanityClient from "@sanity/client" const config = { dataset: process.env.NEXT_PUBLI ...

Error encountered when attempting to retrieve token from firebase for messaging

I am currently working on implementing web push notifications using Firebase. Unfortunately, when attempting to access messaging.getToken(), I encounter an error stating "messaging is undefined." Below is the code snippet I am utilizing: private messaging ...

Filtering out specific properties from an element within a JavaScript forEach loop

const findBloodType = bloodCodeArray.find(bloodCode => bloodCode.code.toUpperCase() === bloodType.toUpperCase()).code; In my Angular code, I am trying to retrieve just the 'code' property of the 'bloodCode' element using a callback ...

Attempting to send numerous identifiers in an API request

I encountered a problem while working on a function in Angular that involves pulling data from an API. My goal is to enhance a current segment to accommodate multiple IDs, but I face difficulties when attempting to retrieve more than one ID for the API que ...

Customize Bottom Navigation Bar in React Navigation based on User Roles

Is it possible to dynamically hide an item in the react-navigation bottom navigation bar based on a specific condition? For example, if this.state.show == true This is what I've attempted so far: const Main = createBottomTabNavigator( { Home: { ...

Obtain the specific key's value from a new Map state

In my code, I've defined a variable called checkedItems as a new Map(); When I try to console.log(checkedItem), the output is as follows: Map(3) {"1" => true, "1.5" => true, "2" => false} Is there a way for me to ...

Discover the HTML of a different website using Javascript

I'm currently developing a basic webcrawler that will display all the links found on a specified website. Here's what I envision my program doing: - enter a URL: http://www.example.com/ - the program retrieves the HTML source and locates all th ...

Dynamic Bootstrap Modal Widget

I have been attempting to create a dynamic modal using Twitter Bootstrap as shown below: $('#myModal').on('hide', function () { $(this).removeData('modal'); $('.loading-modal').remove(); }) Although it rel ...

Are arrays being used in function parameters?

Can the following be achieved (or something similar): function a(foo, bar[x]){ //perform operations here } Appreciate it in advance. ...

Updating the chosen option using jQuery

Is there a way to change the currently selected option using jQuery? <select name="nameSelect" id="idSelect"> <option value="0">Text0</option> <option value="1">Text1</option> <option value="2" selected>Text ...

Issue: $injector:unpr Angular Provider Not Recognized

I've recently developed an MVC project and encountered an issue regarding the loading of Menu Categories within the layout. <html data-ng-app="app"> . . . //menu section <li class="dropdown" ng-controller="menuCategoriesCtrl as vmCat"> ...

Using request-promise from npm, send a request with a self-generated certificate in JavaScript

When trying to make a simple request using the request-promise library, I encountered an error due to having a self-signed cert in my chain. This is a requirement that cannot be avoided. Fortunately, with NPM, I was able to specify the cert for installing ...

Generating text upon clicking by utilizing vue apex charts dataPointIndex

Is there a way to populate a text area on click from an Apex chart? The code pen provided below demonstrates clicking on the bar and generating an alert with the value from the chart. Instead of displaying this value in an alert, I am looking to place it o ...

Buttons within the Bootstrap carousel caption cannot be clicked

I am currently designing a webpage with a Bootstrap carousel that includes a paragraph caption and two buttons. However, the buttons are not functioning as clickable links - when clicked, nothing happens. {% block body %} <div id ="car-container"> ...

Node.js/TypeScript implementation of the Repository design pattern where the ID is automatically assigned by the database

Implementing the repository pattern in Node.js and Typescript has been a challenging yet rewarding experience for me. One roadblock I'm facing is defining the create function, responsible for adding a new row to my database table. The interface for ...

AJAX response from open cart is returning null JSON data

Hey there, I'm having a problem with my ajax request. It seems like I keep receiving a null value for json. Let me show you the JavaScript code... <script> $(document).ready( function() { $('#donate-box-submit').on('click' ...