[英]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
.我遇到的问题是定义
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?有没有办法定义这样的数据,这将是一个递归树?
For the purposes of the React component we don't need any conditionals or generics or anything fancy.对于 React 组件,我们不需要任何条件或 generics 或任何花哨的东西。 @jonrsharpe has the right idea in his comment.
@jonrsharpe 在他的评论中有正确的想法。 A
Tree
is an object where each key is a string
and each value is either a string
or another Tree
. Tree
是 object ,其中每个键都是string
,每个值都是string
或另一个Tree
。
interface Tree {
[key: string]: Tree | string
}
function RecursiveList({ list, path = [] }: {list: Tree, path?: string[]}) {
This works perfectly in the component.这在组件中完美运行。 The
value
inside your Object.entries
has type string | Tree
Object.entries
中的value
具有类型string | Tree
string | Tree
. string | Tree
。 If it's a string
we print it, and if it's a Tree
we render another RecursiveList
from this tree.如果它是一个
string
,我们打印它,如果它是一个Tree
,我们从这棵树渲染另一个RecursiveList
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.