I have elements which have sub-elements that are structured the same as their parent. When I create types of them using TypeScript, I am having some errors. How can I solve that issue?
type RowRecord = Record<string, CellData>;
type CellData = string | number | RowRecord;
Errors:
- Type alias 'CellData' circularly references itself.
- Type alias 'RowRecord' circularly references itself.
Example record:
{
"id": "60f49dbb3ee1a9241749abb6",
"gender": "female",
"firstName": "Millicent",
"lastName": "Harrington",
"birthDate": "2013-05-14T04:35:49.400Z",
"age": 8,
"email": "[email protected]",
"address": {
"country": "USA",
"state": "Utah",
"city": "Cecilia",
"street": "Newkirk Placez",
"houseNumber": 969
}
}
CodePudding user response:
You can do by expanding Record
to the object it represents
type RowRecord = { [K in string]: CellData }; // or { [k: string]: CellData }
type CellData = string | number | RowRecord;
TypeScript doesn't allow your definition because Record<string, CellData>
is eagerly evaluated. If you give TS an object type, then TypeScript recognizes that it can defer the evaluation of that type, permitting a recursive definition.