递归类型(Recursive Type)
一句话解释
递归类型引用自身——适用于树、JSON、嵌套菜单和分形数据结构。
用大白话说
递归类型是在自己定义中引用自身的类型。这让你可以描述任意深度的嵌套结构。常见示例:
- JSON——
type JSON = string | number | boolean | null | JSON[] | { [key: string]: JSON } - 树——
type Tree<T> = { value: T; children: Tree<T>[] } - 链表——
type ListNode<T> = { value: T; next: ListNode<T> | null }
TypeScript 能很好地处理递归类型,但非常深的嵌套可能触及递归限制。用于自然递归的数据结构。
示例
typescript
// JSON type
type JSON = string | number | boolean | null | JSON[] | { [key: string]: JSON };
// Tree structure
type TreeNode<T> = {
value: T;
children: TreeNode<T>[];
};
const tree: TreeNode<string> = {
value: "root",
children: [
{ value: "a", children: [] },
{ value: "b", children: [{ value: "c", children: [] }] },
],
};TreeNode<T> 为 children 引用自身。JSON 为数组和对象引用自身。这实现了任意深度的嵌套。
常见混淆
容易混淆的对象: 泛型类型
关键区别: 泛型类型参数化另一个类型(List<T>)。递归类型引用自身(Tree<T> = { children: Tree<T>[] })。类型可以同时是递归和泛型的——TreeNode<T> 既是 T 的泛型,也是自身的递归。
相关术语
相关资源
相关课程
- TypeScript 高级类型
递归类型。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。