4 min read
•Question 42 of 48hardWhat are Recursive Types in TypeScript?
Types that reference themselves.
What You'll Learn
- Recursive type patterns
- Common use cases
- Avoiding infinite recursion
Basic Recursive Type
code.tsTypeScript
// Tree structure
interface TreeNode {
value: string;
children: TreeNode[];
}
const tree: TreeNode = {
value: "root",
children: [
{ value: "child1", children: [] },
{ value: "child2", children: [
{ value: "grandchild", children: [] }
]}
]
};JSON Type
code.tsTypeScript
type JSONValue =
| string
| number
| boolean
| null
| JSONValue[]
| { [key: string]: JSONValue };Deeply Nested Partial
code.tsTypeScript
type DeepPartial<T> = {
[K in keyof T]?: T[K] extends object
? DeepPartial<T[K]>
: T[K];
};
interface Config {
server: {
host: string;
port: number;
};
}
type PartialConfig = DeepPartial<Config>;
// All nested properties optionalLinked List
code.tsTypeScript
interface ListNode<T> {
value: T;
next: ListNode<T> | null;
}
const list: ListNode<number> = {
value: 1,
next: {
value: 2,
next: {
value: 3,
next: null
}
}
};