Home > Net >  Combine fields from two type definitions in Typescript
Combine fields from two type definitions in Typescript

Time:06-29

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.

CodePudding user response:

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 }));
  • Related