2021年3月19日星期五

How do you define a type which could be any subtree of an object recursively?

Imagine that I have the following data:

const data = {    animilia: {      chordata: {        mammalia: {          carnivora: {            canidae: {              canis: 'lupus',              vulpes: 'vulpe'            }          }        }      }    },  } as const;  

Now I have a component which will render this out as a tree, recursively, like so:

function RecursiveList({ list, path = [] }) {    return (      <ul>        {Object.entries(list).map(([key, value]) => {          const reactKey = [...path, key].join('.');          if (isString(value)) {            return <li key={reactKey}>{value}</li>          }          return (            <Fragment key={reactKey}>              <li>{key}</li>              <RecursiveList list={value} path={[...path, key]} />            </Fragment>          )        })}      </ul>    );  }  

The problem I'm having is defining the type for list. In theory, it should be the provided type at any depth. I tried the following:

type Tree<T extends string | Record<string, unknown>> = {    [K in keyof T]: T extends string ? string : Tree<T>;  }  

This doesn't seem to accurately reflect the type.

Is there a way to define data like this that would be a recursive tree?

https://stackoverflow.com/questions/66707994/how-do-you-define-a-type-which-could-be-any-subtree-of-an-object-recursively March 19, 2021 at 08:15PM

没有评论:

发表评论