skip to Main Content

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


  1. The problem is that T can be an object with anything as value. You use data[index][col] as a string without converting it to a string, and that is the error. That is why String(el[col]) worked. If you were to use msg.concat('' + el[col]); or msg += el[col]; it would work too.

    Login or Signup to reply.
  2. To get types to work, you can make T extend an array.

    You can then use keyof T[number] or even T[0], seen as all elements are the same.

    eg.

    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 extends any[]>(data: T, cols: Array<keyof T[number]>) {
      data.forEach((el) => {
        let msg = '';
        cols.forEach((col) => {
          msg = msg.concat(el[col]);
        });
        console.log(msg);
      });
    }
    
    printLastName(data, ['name', 'lastname']);
    //printLastName(data, ['name', 'error']);  <-- Error
    
    

    TS Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search