In TypeScript, what do we call a property that is accessed dynamically?

I have a reusable function that can be used on various properties of a custom type. Here's an example:

interface MyType {
  prop1: string;
  prop2: number;
}
type MyTypeKey = keyof MyType;

const testValue = (
  obj: MyType,
  property: MyTypeKey,
  value: any, // <-- what type should go here?
) => {
  if (obj[property] === value) {
    console.log("do something");
  }
}

testValue({prop1: "a", prop2: 1}, "prop1", "okay"); // should be okay
testValue({prop1: "a", prop2: 1}, "prop2", "oops"); // should be error

However, I'm unsure about the type of the property value. Can anyone guide me on how to handle this?

(I am new to javascript/typescript, so please excuse any small errors or suboptimal practices)

Answer №1

To show the key, use a generic argument. This key allows you to search for it in MyType to determine the type of value associated with it. The generic function requires the value argument to match that type.

interface MyType {
    prop1: string;
    prop2: number;
}

const testValue = <K extends keyof MyType>(
    obj: MyType,
    property: K,
    value: MyType[K],
) => {
    if (obj[property] === value) {
        // ...
    }
}

declare const obj: MyType;
// Correct
testValue(obj, 'prop2', 3);
// Incorrect
testValue(obj, 'prop2', 'a');

If you want a more adaptable function that can validate any object without specifying MyType, create another generic type for the object.

const testValue = <O extends object, K extends keyof O>(
    obj: O,
    property: K,
    value: O[K],
) => {
    if (obj[property] === value) {
        // ...
    }
}

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

retrieving class instances from a Firebase database

I have a new group called GroupA group A { value1: string; value2: string; total(): number { return value1 + value2; } } I want to store instances of GroupA in my database, but when I retrieve them, they are in Object format which does not a ...

Exploring ES6: Harnessing the Power of Classes

I am currently learning the ES6 syntax for classes. My background is in C#, so I apologize if my terminology is not accurate or if something seems off. For practice, I am working on building a web app using Node and Express. I have defined some routes as ...

outputting javascript within php

I'm struggling to extract the data returned by AJAX after a successful call. Instead of just getting the words printed by my JavaScript code, I end up with the entire script that is echoed in the PHP file. What I really need are only the words outputt ...

Avoiding overlapping in setTimeOut when using jQuery.hover()

Looking to trigger an effect one second after the page loads, and then every 3 seconds in a loop. When the user hovers over a specific element with the ID #hover, the effect should pause momentarily. It should then resume 2 seconds after the user stops hov ...

Exploring Next.js: Leveraging fetch to retrieve data in getServerSideProps and passing it to the client via query parameters

I'm utilizing a getServerSideProps function on the directory page. pages/catalog/index.js export async function getServerSideProps(ctx) { const response = await fetch( `http://someDomen.com/api/ipro/catalog?${ctx?.query?.page ? `page=${ctx.quer ...

Obtain the union type by extracting values from an indexed object

Suppose there is an indexed type: type X = { a: 'A', b: 'B' } Is there a way to derive the following type from it: type V = 'A' | 'B' without using an explicit method like this: type V = X['a'] | X[& ...

I am currently running a recursive loop to fetch data from MongoDB. However, the Express.js function runs through the entire script before the data can be successfully returned

Can someone assist me with setting up my Express route to handle the return of data from a recursive function that involves promises and fetching MongoDB data? Currently, my route is executing immediately without sending the data back to the client. The da ...

Connecting an HTML box to a JavaScript function for the desired outcome: How to do it?

My goal is to connect the input box with id="b" (located inside the div with id="but1") with a JavaScript function that calculates values within an array. Although my junior logic review didn't detect any issues in the code, what mistakes could I have ...

Using Jquery to handle different status codes in an Ajax request

Currently, I am handling statusCode of 200 and 304 in a jQuery Ajax call. Additionally, I have defined an "Error" function to catch any errors that may occur. If a validation message is related, we specify the status code as 400 - Bad Request. In this sc ...

Ensure that a JavaScript prompt appears when a form is selected in a dynamic HTML field

My PHP script generates a table form with results from a database query for users to edit records. The form can display up to 30 records. If the VoidTag checkbox is checked when the form is submitted, I want the user to confirm this action. If it is not ...

I'm looking for a method in JavaScript that can search through my XML file to locate specific attributes and return the entire parent element containing that attribute. Can anyone help with

I'm completely new to XML and Javascript. I currently have this code in my HTML file: <select id="eigenschaften" name="eigenschaften" type="text" onchange=""> <option value="">Choose Property</option> <option value="soci ...

Initiating a SOAP request to utilize your custom services

Currently, I am in the process of creating a web application that includes providing various web services. After completing the domain model, we are now focusing on implementing both the User Interface (UI) and controller. The controller will consist of t ...

The chrome extension is not displaying any output in the console, even though there are no errors

https://i.sstatic.net/YhEKl.png I am currently working on creating a browser extension that will monitor the xhr section of the devtools network tab. To start off, I have kept my background script as simple as possible. Even though there are no errors whe ...

Using Vue.js to conditionally render content based on changes in a variable

I am facing a challenge in rendering a new element once the boolean variable waiting changes to true. The issue arises when transitioning from one v-if statement to another, as the boolean does not update until the first statement is completed. How can I s ...

Secure mustache templates for data validation

Is there a method to achieve the following?: my-custom-template.mstach Hello {{name}}! script.js import { readFileSync, writeFileSync } from 'fs'; import * as Mustache from 'mustache'; export interface Person { name: string; } ...

Convert a file into an empty array when sending a post request from Angular to Laravel

I am currently working on a simple Laravel 5 post request that aims to achieve the following tasks: Save some data to a database. Store a file (image) in public storage with a name consisting of 20 random numbers followed by '.jpg'. Save a URL ...

The error "redux-persist undefined is not an object (evaluating 'action.type')" indicates that there is an issue with the

Struggling with an error in my Redux project using Redux Persist and React Native Looking for help to fix an error in my Redux setup. I am using Redux with React Native and trying to create a store with a reducer. The error I am encount ...

The E.js Template encountered an error with an unexpected token "else"

I am in the process of creating a website quickly using e.js & Express. However, I am encountering some problems when trying to use an if-else statement within e.js tags. The if statement works fine, but as soon as I add an else statement, things start t ...

Is it possible to disable a function by clicking on it?

I currently have a website that is utilizing the following plugin: This plugin enables an image to be zoomed in and out through CSS transforms, with default controls for zooming in and out. My goal is to incorporate a reset button that returns the image ...

Converting Unicode to characters using Javascript

There are instances where special characters are converted into Unicode, like in the string below. How can we revert them back into special characters? Example: ///Incoming string "ਸਪੋਰਟਸ ਫੈਕਟਰੀ &#8216;ਚ ਅੱਗ ਨ ...