Hi I want to create a function that takes two parameters an array of objects "T[]" and a array of fields of the T. However I keep getting the following problem in the line where I call 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 is the following:
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']);
2
Answers
The problem is that
T
can be an object with anything as value. You usedata[index][col]
as a string without converting it to a string, and that is the error. That is whyString(el[col])
worked. If you were to usemsg.concat('' + el[col]);
ormsg += el[col];
it would work too.To get types to work, you can make T extend an array.
You can then use
keyof T[number]
or evenT[0]
, seen as all elements are the same.eg.
TS Playground