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 create recursive type?

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:

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

{
    "id": "60f49dbb3ee1a9241749abb6",
    "gender": "female",
    "firstName": "Millicent",
    "lastName": "Harrington",
    "birthDate": "2013-05-14T04:35:49.400Z",
    "age": 8,
    "email": "millicent@harrington.com",
    "address": {
      "country": "USA",
      "state": "Utah",
      "city": "Cecilia",
      "street": "Newkirk Placez",
      "houseNumber": 969
    }
  }

>Solution :

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.

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