Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to type custom object?

I am just learning TypeScript and have a question. I am receiving data from the API and would like to type it.

interface FieldData {
  type: number,
  other: string
}

const AAA = 'aaa';
const BBB = 'bbb';
const CCC = 'ccc';


const fields: Array<FieldData> = await getFields();

const myData: any = {
  [AAA]: [],
  [BBB]: [],
  [CCC]: []
};

fields.forEach((field: any) => {
  if (field.type === 1) {
    myData[AAA].push(field);
  } else if (field.type === 2) {
    myData[BBB].push(field);
  } else {
    myData[CCC].push(field);
  }
});

How do I create a typing for a myData object? I don’t want to use any type.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If the AAA etc properties may vary, and can’t be completely static, write them with as const, and note that their array values are of Array<FieldData>.

const myData = {
  [AAA]: [] as Array<FieldData>,
  [BBB]: [] as Array<FieldData>,
  [CCC]: [] as Array<FieldData>
};

fields.forEach((field) => {

or

const myData: Record<typeof AAA | typeof BBB | typeof CCC, Array<FieldData>> = {
  [AAA]: [],
  [BBB]: [],
  [CCC]: []
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading