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']);