0

I am developing a typescript project wherein I get data of the form :

const data1 =  { id: 0, rac: 43, tcreated: "12-04-21", tupdated: "12-09-22", Custname: "A" }

Now I want to filter the columns for further processing dynamically,

const fields = ["id", "tcreated", "Custname"]; 

I found the solution for normal Javascript as

const subset = fields.reduce((a, e) => ((a[e] = data1[e]), a), {});

But the same doesn't work in my typescript React project. I tried various other ways mentioned here but none seem to work on account of type mismatch TS7053. Any ideas?

1 Answers1

0

You have to define an interface like below,

 interface DataConfig {
    [propName: string]: string | number;
  }

  const data1: DataConfig = {
    id: 0,
    rac: 43,
    tcreated: "12-04-21",
    tupdated: "12-09-22",
    Custname: "A"
  };

And mention the element type in the iteration,

 const subset = fields.reduce(
    (a: DataConfig, e) => ((a[e] = data1[e]), a),
    {}
  );
Sarun UK
  • 6,210
  • 7
  • 23
  • 48