Home > Mobile >  How to type custom object?
How to type custom object?

Time:02-15

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.

CodePudding user response:

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]: []
};
  • Related