Can we utilize the elements in Array<keyof T> as keys in T?

Hello, I am trying to develop a function that accepts two parameters: an array of objects "T[]" and an array of fields of type T. However, I am encountering an issue when I reach the line where I invoke el[col]

    Argument of type 'T[keyof T]' is not assignable to parameter of type 'string'.
  Type 'T[string] | T[number] | T[symbol]' is not assignable to type 'string'.
    Type 'T[string]' is not assignable to type 'string'.(2345)

The code snippet in question is as follows:

interface user {
  name: string;
  age: number;
  lastname: string;
}

const data: user[] = [
  {
    name: 'foo',
    age: 21,
    lastname: 'bar',
  },
  {
    name: 'foo',
    age: 21,
    lastname: 'baz',
  },
  {
    name: 'foo',
    age: 21,
    lastname: 'bax',
  },
];

function printLastName<T>(data: T[], cols: Array<keyof T>) {
  data.forEach((el) => {
    let msg = '';
    cols.forEach((col) => {
      msg = msg.concat(el[col]);
    });
    console.log(msg);
  });
}

printLastName(data, ['name', 'lastname']);

Answer №1

The issue arises from the fact that the variable T can have any value type, including objects. When you try to use data[index][col] as a string without converting it properly, it results in an error. This is why String(el[col]) was successful in resolving the problem. Alternatively, using msg.concat('' + el[col]); or msg += el[col]; would also yield the desired outcome.

Answer №2

If you want to ensure types work correctly, one option is to have T extend an array.

Then, you can utilize keyof T[number] or simply T[0], as all elements are consistent.

For example:

interface person {
  name: string;
  age: number;
  lastname: string;
}

const dataset: person[] = [
  {
    name: 'John',
    age: 30,
    lastname: 'Doe',
  },
  {
    name: 'Jane',
    age: 25,
    lastname: 'Smith',
  },
  {
    name: 'Bob',
    age: 45,
    lastname: 'Johnson',
  },
];

function displayLastName<T extends any[]>(data: T, columns: Array<keyof T[number]>) {
  data.forEach((element) => {
    let message = '';
    columns.forEach((col) => {
      message = message.concat(element[col]);
    });
    console.log(message);
  });
}

displayLastName(dataset, ['name', 'lastname']);
//displayLastName(dataset, ['name', 'error']); <-- Produces an error

TS Playground

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

Issue with Firefox compatibility in Backbone.js

Greetings! I am currently utilizing Backbone.js and require.js for my application, experiencing difficulty with template rendering in Firefox. Interestingly, it works without issues in both Chrome and IE. Allow me to present the code responsible for rende ...

Is the condition failing to evaluate for all td elements?

I am currently dealing with an HTML table. When I select a checkbox, I aim to compare the values of the cells in each row. This comparison works correctly for the first row, but it does not work for any subsequent rows. HTML Code - <form role="fo ...

What is the method for incorporating opacity into the background color CSS attribute using a Fluent UI color?

Currently, my challenge involves applying opacity to a background color sourced from the fluent UI library, which utilizes Design Tokens. Typically, I would add opacity to a background color like this: background-color: "rgba(255, 255, 255, 0.5)" However ...

Exploring Javascript through Python using Selenium WebDriver

I am currently attempting to extract the advertisements from Ask.com, which are displayed within an iframe generated by a JavaScript script hosted by Google. Upon manually navigating and inspecting the source code, I can identify the specific element I&ap ...

Creating a visual representation of data using Google Charts to display a stacked bar chart

I wrote a script to display a stacked Google chart using JSON data stored on the wwwroot directory - <html> <head> <title>DevOps Monitoring Application</title> <link rel="icon" type="image/png" hr ...

Error: Unable to convert Mongoose object to ObjectId

Currently tackling an issue with my small blog app and I seem to be stuck at this error- { "message": "Cast to ObjectId failed for value \" 597c4ce202ca9c353fc80e8a\" at path \"_id\" for model \"Blog\"", "name": "CastErr ...

Bring in styles from the API within Angular

My goal is to retrieve styles from an API and dynamically render components based on those styles. import { Component } from '@angular/core'; import { StyleService } from "./style.service"; import { Style } from "./models/style"; @Component({ ...

What is the best way to incorporate a dynamic background in NextJS using Tailwind?

I have a poster image that I want to use as a background image, fetched from MovieDb. I tried putting it inside the className like this: className={bg-[url('${path}')] h-screen bg-cover bg-center text-white border-b-8 border-b-solid border-b-sla ...

Extracting a particular element from a sophisticated auto-complete DOM structure by drilling down into the $scope

After spending a significant amount of time trying to solve this problem, I find myself at a dead end. The simplicity of using jQuery makes me reconsider Angular, but perhaps my approach is flawed. In this scenario, the DOM structure looks like this: < ...

Separate the selected option in the TEXTAREA by commas to make it easier to

Can you assist me with integrating this example? I have the following elements: When adding a textarea, I require an option to be selected and separated by a comma. For instance: Here I will select an option: Subsequently, this chosen option must be ad ...

Having trouble with setting up the next image configuration for graphcms' images

I've been using graphcms solely for my image assets and trying to integrate them into my Next JS (v12.0.1) frontend. However, I keep getting the error message hostname not configured in next.config.js, even though I have already specified it in my nex ...

Exploring the .map() Method in ReactJS

Would it be feasible to integrate another Postgres database table into the current mapping displayed in this code? It would be ideal if it could be done using some sort of array function. {items.map(item => ( <tr key={item.id}& ...

A Multilingual Application developed using either AngularJS or the Ionic Framework

Having recently delved into both AngularJS and the Ionic Framework, my background is primarily in Microsoft technologies. I am currently working on developing an app that supports three languages: English, Arabic, and French. Drawing from my experience wi ...

Enabling table row scrolling with keyboard navigation in React

Struggling to figure out how to make my table scroll while navigating through the rows using the onKeyDown event. It seems that the event isn't updating when using the keyboard, even though the highlighting of the selected row with selected is working ...

In the ajax call, an empty JSON array object is sent as the data

Utilizing JSON data as a parameter for an ajax call: var startDate = dateFormatForSave($("#start_date").val().trim()); var arrayOfStudentsInfo = []; var table = $("#selected_students"); table.find('tr').each(function(i, el) { var rowId = $( ...

Using form submission to implement reCAPTCHA v3 in g-recaptcha

Is the Recaptcha API causing trouble? I have the key on both the submit button and the form tag, but it's only sending the sitekey without generating tokens. Any suggestions are welcome. You can either use the key in the form tag: <form method=&qu ...

Error encountered with AngularJS code when attempting to load content from another page using ajax

I'm currently tackling a challenge with AngularJs and php. Whenever I try to load content from another page, AngularJs seems to stop working. Let me provide you with a sample code snippet to illustrate my issue. main-page.php <div id="form-secti ...

What is the best way to retrieve data from Firebase and then navigate to a different page?

I am facing an issue with my app where I have a function that retrieves data from Firebase. However, after the completion of this Firebase function, I need to redirect it to another page. The problem is that when I press the button, the redirection happe ...

React/MaterialUI - Is there a way to customize the placeholder text for my multi-input field beyond the provided options?

I have a dropdown menu that accepts two JSON objects, symbol and company. export default function SymbolInput() { const [data, setData] = useState({ companies: [] }); const classes = useStyles(); useEffect(() => { Axios.get(" ...

Ensure the smooth scrolling feature is activated by adding an active class when either clicking or manually scrolling the

I have a script that enables smooth page scrolling, but I want it to automatically add an "active" class to the link corresponding to the section currently in view. While there are similar solutions out there, most of them only apply the class when the lin ...