Tree types
- TypeScript course
- Advanced
- Lesson 10/57
- 4 min
Learn to express tree structures as types.
What are tree types?
A tree type is defined by each node containing a value and an array of child nodes. The cocuklar: Dugum[] field references the same type again; this allows unlimited branching. File systems, categories, and organization structures are modeled this way.
type Node = {
name: string;
children: Node[];
};Tree depth
In a tree type, since each node carries child nodes within itself, the data can be of unlimited depth. Thanks to cocuklar: Dugum[], each child node conforms to the same structure. At leaf nodes, cocuklar is an empty array and branching ends.
Practice Create a tree object
Define a recursive type named Dugum: { ad: string; cocuklar: Dugum[] }. The kok variable should be of type Dugum with value { ad: "kok", cocuklar: [{ ad: "cocuk1", cocuklar: [] }] }. Print kok.ad with console.log.
Starter code
// Dugum adinda recursive type tanimla
// ad ve cocuklar alanlari olsun
// kok nesnesini bir cocukla tanimla
// kok.ad yazdirSample solution
type Dugum = {
ad: string;
cocuklar: Dugum[];
};
const kok: Dugum = { ad: "kok", cocuklar: [{ ad: "cocuk1", cocuklar: [] }] };
console.log(kok.ad);Expected output
kok
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the cocuklar field of a leaf node in a tree type?
- null
- Itself again
- Empty array [] Correct answer
- undefined
Explanation: A leaf node has no children, so its cocuklar field is an empty array []; not null or undefined.
2 Children field type
type Dugum = {
ad: string;
cocuklar: ____[];
};
type Dugum = {
ad: string;
cocuklar: Dugum[];
};
Explanation: In a tree type, the cocuklar field is of type Dugum[]; each child node conforms to the same structure.
3 Tree type concepts
| Term | Meaning |
|---|---|
cocuklar: Dugum[] |
Child node array |
ad: string |
Node name |
yaprak |
Childless node |
Dugum |
Self-referencing type |