5

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
    }
  }
0

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I have tried your solution and it worked. But I don't know about such "{ [k: string]: CellData }" data structure. Could you tell me what is this or recommend me any source about it?
[k: string] there is an index signature, [k in string] is a mapped type

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.