Tips on transforming a string into a string attribute

I need help creating a Typescript function that takes 2 arguments, where the second argument is always a string type. This function should apply the second argument as a property on the first argument.

For example:

let x = measure('Hello', 'length'); // should return 'Hello'.length
// => x = 5

Any suggestions on how I can convert the string 'length' into a property of 'Hello' to achieve the desired result?

Answer №1

Upon grasping your concept:

function measure(obj: any, property: string): any {
    return obj[property];
}

let x = measure('Hello', 'length');
console.log(x); // 5

(playground code here)


Edit

An alternative approach could be:

function measure<T, K extends keyof T>(obj: T, property: K): T[K] {
    return obj[property];
}

This version allows the compiler to deduce the returned value's type and ensures usage of only existing property names, as demonstrated below:

let x = measure('Hello', 'lengthy'); // triggers error

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

ScriptManager is not accessible in the current ASP.Net Core Razor Page context

I'm facing an issue where I have a view (such as Index.cshtml) and a page model (like Index.cshtml.cs). In the view, there's a JavaScript function that I want to call from the OnPost() method in the page model. I tried using ScriptManager for thi ...

JavaScript encountering a NaN value

I'm encountering an issue where I am receiving a NaN when attempting to summarize columns of a report. Additionally, my query is only retrieving 1 row of data, but the grid is displaying 2 rows. Does anyone have any suggestions on how to resolve this ...

Is there a way to access the complete conversation using just the tweet's original ID?

I am in search of a straightforward and refined solution for this task, specifically using pure JS/Node. It would be great if there is a function that takes the tweet ID as input and outputs a JSON object containing the complete conversation. While I kno ...

employing the jQuery method .replaceWith()

My div contains the following elements: <div id = "menu"> <a>Element1</a><br/> <a>Element2</a><br/> <a>Element3</a><br/> </div> Whenever ...

Is it possible to monitor child component values within the parent component without relying on emit?

I created a unique component named HobbyForm, which consists of a simple form with two controls - a checkbox and an input field. This particular component is being utilized within a parent component called Content, alongside similar 'form' compon ...

Techniques for implementing a JS script within a useEffect hook in a functional component

I am currently working on a useEffect hook in my project, within which there is an if-else block that includes a Javascript function called 'B1.X.Change' inside the else statement. However, I am facing difficulty binding 'B1.X.Change' t ...

Unable to resolve the "Error: posts.map is not a function" issue

I am currently developing a social media-like web application. One of the features I'm working on is to display all posts made by users. However, when I run my code, it doesn't show anything and I get an error in the console that says "Uncaught T ...

How can you center the body of a webpage while using the zoom in and zoom out features in HTML5?

What is the best way to maintain body alignment while zooming in and out on a web page? <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> body { font-family: 'Merriweather Sans&apos ...

What is the correct way to perform a push-up?

Currently, I am working on creating a login page using React. After the login process is completed, I want my React application to redirect to the page called FrontFeed. For this redirection, I am utilizing the code snippet this.props.history.push('/f ...

Develop a GWT overlay specifically designed for a deeply nested JSON data structure

Recently stumbling upon this amazing site, I find myself compelled to seek your assistance with a particular issue: How do you go about accessing the fields within the nested JSON object labeled "flightLegs" from the main JSON object "flights"? When it c ...

What is the best way to compare two sets of arrays and generate a new one with unique key-value pairs?

I have two arrays and I want to extract specific key-value pairs from each and combine them into a new array, handling duplicate entries. First Array : [ {id: 2, name: "HSBC", status: "YES"}, {id: 3, name: "Morgan Stanley&quo ...

Experimenting with PIXI.js and Jest within a React Single Page Application

I am currently working on a react application that utilizes PIXI.js and @inlet/react-pixi for animations. During testing with Jest, I encountered the following errors: Error: Uncaught [TypeError: Cannot read properties of null (reading 'stage' ...

What is the best way to access and compare the values within each <td> element?

, my code looks like this: <table id="table_append"> <tr class='text-center'>" + <td>1</td> <td class="codeverify">025</td> <td> Data1 </td> </tr> ...

If the submission fails, then activate the selection of the ID

My dilemma is with a <select> element that initiates an AJAX call to the backend to display or hide additional <select> options based on user selection: $('#select1').on('change', function() { // Fetch fruit details ...

Utilizing Angular to Toggle Visibility with Button Directives

Within my main view, I have three directives that each display different sets of data. <div> <sales-view></sales-view> </div> <div> <units-view></units-view> </div> Addi ...

NodeJs error: the response status function is missing

Encountering the error message "res.status is not a function" while working with this route. Any suggestions on how to resolve this issue? Thank you! exerciseRouter.post('/update/:id', (res, req) => { Exercise.findById(req.id) .th ...

When utilizing ng2-bootstrap, there is no directive that is defined with the "exportAs" attribute set to "bs-modal"

I found a tutorial that I am trying to emulate from this website However, when I insert the template into my HTML file <div class="modal fade" bsModal #staticModal="bs-modal" [config]="{backdrop: 'static'}" tabindex="-1" role="dialog" ...

Show an image on a webpage using a URL from a Firebase database with HTML

How can I dynamically display images from URLs in my table? My table automatically increments every time new data is added, but I'm having trouble displaying images. The table already shows the URL where the image should be displayed. Here is the ou ...

How to extract keys with the highest values in a JavaScript hashmap or object

Here is an example for you to consider: inventory = {'Apple':2, 'Orange' :1 , 'Mango' : 2} In this inventory, both Apple and Mango have the maximum quantity. How can I create a function that returns both Apple and Mango as t ...

Selenium: Extracting innerHTML code source that is not visible in the 'inspect element' view

Hello! After extensive research across the internet, I have not encountered a problem similar to mine. I am attempting to extract data using Selenium from ''. I have navigated through the necessary steps to reach the desired page. Upon reachin ...