简体   繁体   中英

How to define a tree type in TypeScript?

I wrote a tree like type as below:

type ReactNode = ReactChild | Array<ReactNode> 

but editor told me that

TS2456: type alias 'ReactNode' circularly references itself.

How to solve fix this error?

There's a problem with recursions in type aliases, as shortly explained in this issue :

type aliases are not like interfaces. interfaces are named types, where as type aliases are just aliases. internally as well they are treated differently, the compiler aggressively flatten types aliases to their declarations.

There's a longer discussion here: allow recursive generic type aliases .

In your case, you can do something like:

interface ReactNodeArray extends Array<ReactNode> {}

type ReactNode = ReactChild | ReactNodeArray;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM