1

I have a API call that returns the following JSON object:

{
  resultList:[
    {
       subField: {
          a: number,
          b: string
       },
       subField2:{
          c: number,
          d: number
       }
    },
    {
      ...
    }
  ]
}

I made two types to capture these sub-fields:

type SubField1= {
   a: number;
   b: string;
}
type SubField2= {
   c: number;
   d: number;
}

I also need to combine these sub-field data to populate a table and I was wondering what's the best way to do it that doesn't involve manually typing the fields out? I tried this:

type TableData = {
   ...SubField1,
   ...SubField2
}

But got an error message from my IDE that says:

Member 'SubField1' implicitly has an 'any' type, but a better type may be inferred from usage.
Liumx31
  • 1,190
  • 1
  • 16
  • 33
  • https://stackoverflow.com/questions/27325524/is-it-possible-to-combine-members-of-multiple-types-in-a-typescript-annotation this looks like it may answer your question – Raymi306 Jun 28 '22 at 15:38

1 Answers1

2

I'm not sure what you are trying to achieve, but you can declare a new type with the combined properties like this:

type TableData = SubField1 & SubField2;

The spread operators will only work when you assign a variable, for example:

const tableData = resultList.map(v => ({ ...v.subField1, ...v.subfield2 }));
kristype
  • 111
  • 5
  • Maybe you could also suggest the "|" operator and is use, which could also be relevant to the OP – Arjan Jun 28 '22 at 15:50