Having trouble converting from JavaScript to TypeScript, encountered an error in the process

Seeking assistance with transitioning JavaScript code to TypeScript.

const profiles = [{
    name: "kamal",
    age: "20",
    designation: "developer",
    grade: "A",
  },
  {
    name: "arun",
    age: "25",
    designation: "developer",
    grade: "A",
  },
  {
    name: "chan",
    age: "23",
    designation: "developer",
    grade: "A",
  },
];

function profileLookup(name, prop) {
  for (let i = 0; i < profiles.length; i++) {
    if (profiles[i].name === name) {
      if (prop in profiles[i]) {
        console.log(profiles[i][prop]);
      }
    }
  }
}

profileLookup("arun", "age");

Answer №1

Below is the provided sample code snippet.

    type User = {
    name: string;
    age: number;
    role: 'developer' | 'QA' | 'manager';
    grade: 'A' | 'B' | 'C';
}

const users: User[] = [{
    name: "kamal",
    age: 20,
    role: "developer",
    grade: "A",
},
{
    name: "arun",
    age: 25,
    role: "developer",
    grade: "A",
},
{
    name: "chan",
    age: 23,
    role: "developer",
    grade: "A",
},
];

function userLookup(name:string, attribute:keyof User) {
    for (let i = 0; i < users.length; i++) {
        if (users[i].name === name) {
            if (attribute in users[i]) {
                console.log(users[i][attribute]);
            }
        }
    }
}

userLookup("arun", "age");

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

Navigate through the list of options by scrolling and selecting each one until the desired element is

Hey, I've got this AngularJs directive that selects an item based on the "key-pressed" event, and it's working perfectly. The issue arises when there is a scroll bar since the elements get hidden, making it difficult for me to see them. You can ...

Tips for incorporating an anchor tag within an img tag in HTML?

Is it possible to add an anchor tag inside an img tag in HTML? <img src="img.jpg" alt="no img" /> I want to include the following inside the img tag: <a onclick="retake();" > Retake </a> The goal is to allow users to retake a photo by ...

Determine the hexadecimal color value by combining two different colors along with a specified percentage/position

Can a color in the middle of a gradient be calculated? var initialColor = 'FF0000'; var finalColor = '00FF00'; // At 50% between the two colors, it would result in '808000' var middleColor = determineMiddleColor(initialColor ...

When multiple forms have identical input IDs, only the first value is sent using Ajax

As I implement an ajax function to insert data into a database using a form and hidden input type, I encounter an issue where only the value from the first form on the page is being captured. Please see the following code: The Ajax function <script l ...

express/node: You are unable to define headers once they have already been sent to the client

I seem to be running into a problem with my expressJS application. Every time I try to post to a specific route, I keep getting the error message Cannot set headers after they are sent to the client. I've been troubleshooting this issue but can't ...

Nest JS is currently experiencing difficulties with extending multiple classes to include columns from other entities

Currently, I am immersed in a new project that requires me to enhance my entity class by integrating common columns from another class called BASEMODEL. import { Index, PrimaryGeneratedColumn } from "typeorm"; export class BaseModel { @Prima ...

The count of records in MongoDB by the current month

Recently delving into MongoDB, I found myself in need of a way to retrieve the count of posts made in the current month. Keeping timestamps true in my PlateModel model, it appears as follows: { timestamps: true } The current code snippet in my Controller ...

parsing objects within an HTML component in Angular

Is there a way to utilize an object as the @input parameter in HTML? For example: <app-home [param]="user.salary"></app-home> However, the type of my user object is structured like this: user:Person=new Employee(); The classes invol ...

Strategies for capturing POST data sent to a JavaScript webpage

The request is sent from an external source beyond my control xyz.php <form action='https_:_//xyz.com/javascriptFile' method='POST'> <input type='text' name='data' /> </form> to: (My custom f ...

A guide on how to insert content into a text area using a drop-down menu choice

I'm a total beginner at this. Is it possible to use JavaScript to automatically fill in a text area on an HTML form based on what is selected in a drop-down menu? If so, can someone please explain how to achieve this? ...

Changing the color of HTML text based on a variable in Vue JS can be achieved by altering the CSS styles dynamically

I have developed a website that shows values with a set threshold. I now want to change the color of the values when they exceed the threshold, but I am unsure of how to proceed. I want to display consultation.indicateurs.TRS in red when it exceeds the va ...

Exploring Nested Divs with Vue Test Utils

Recently, I came across this shallowMounted vue component: <div class="card p-relative"> <div class="card-header"> <div class="card-title h4"> a lovely title <!----> <!----> </div> </div ...

Angular 6: Utilizing async/await to access and manipulate specific variables within the application

Within my Angular 6 application, I am facing an issue with a variable named "permittedPefs" that is assigned a value after an asynchronous HTTP call. @Injectable() export class FeaturesLoadPermissionsService { permittedPefs = []; constructor() { ...

Ways to loop through an array of daytime values and exhibit just the records for the current week

ng-repeat="day in task.DailyWorks | limitTo : weekdays.length: weekStart" This iteration process enables me to showcase the daily work records in a structured format within the table columns. The feature allows for seamless navigation between different we ...

Display a webpage once its design is completely loaded in Nuxt

I have implemented a layout for my admin pages that displays user information in a consistent format, eliminating the need to fetch this data every time the page reloads. However, I am facing an issue where the page does not wait for the layout to fully l ...

Key-based user retrieval is unavailable in Express, "findAll" can only be done through email

I've created a straightforward Express/Pug application designed for searching users in a database by "email" or by "key". In this setup, each user is assigned a unique string as their key. The structure of my user model and index model files can be se ...

What is the best way to transfer $scope to a service in angular.js?

I have two services listed below. When navigating to a specific URL, I need to resolve "OtherService.promise". However, for certain routes, I would prefer to utilize a scope variable within the AppService method instead of the promise. How can I make thi ...

How can jsPDF be used with Angular2 in Typescript?

Recently, I developed an Angular2 application that is capable of generating JSON data. My main goal was to store this JSON output into a file, specifically a PDF file. This project was built using Typescript. To achieve the functionality of writing JSON d ...

Accessing XML data using Cross-Domain AJAX

New to this! I'm currently working on a client script that requires reading an XML file from another domain. I attempted to utilize JSONP, and while I receive a 200 response, the client is unable to access the data returned for some unknown reason. Tw ...

Experiencing an anonymous condition post onChange event in a file input of type file - ReactJS

When using the input type file to upload images to strapi.io, I noticed that an unnamed state is being generated in the React dev tools. Can someone explain how this happened and how to assign a name to that state? https://i.sstatic.net/ZyYMM.png state c ...