Summary - Recursive types
- TypeScript course
- Advanced
- Lesson 12/57
- 4 min
Write a JSON tree model with recursive types.
Summary - Recursive types
In this group you learned recursive types: self-referencing types model nested structures like linked lists and trees; DeepPartial makes nested objects deeply optional. A JSON tree model references itself in array and object forms alongside a union of primitive types.
type JsonValue =
| string | number | boolean | null
| JsonValue[]
| { [k: string]: JsonValue };Practice Write a JSON tree model
Define a recursive union type named JsonDeger: string | number | boolean | null | JsonDeger[] | { [anahtar: string]: JsonDeger }. The veri variable should be of type JsonDeger with value { ad: "test", yas: 30 }. Print veri["ad"] with console.log.
Starter code
// JsonDeger adinda recursive union type tanimla
// primitif, dizi ve nesne turlerini birlestir
// veri nesnesini tanimla
// veri["ad"] yazdirSample solution
type JsonDeger =
| string
| number
| boolean
| null
| JsonDeger[]
| { [anahtar: string]: JsonDeger };
const veri: JsonDeger = { ad: "test", yas: 30 };
console.log(veri["ad"]);Expected output
test
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What should be the type of array elements in a JSON tree model?
- Only string
- JsonDeger (itself) Correct answer
- any[]
- Only number
Explanation: Elements of a JSON array can themselves be any JSON value; so the array type references itself as JsonDeger[].
2 JSON array self-reference
type JsonDeger =
| string
| number
| boolean
| null
| ____[]
| { [anahtar: string]: JsonDeger };
type JsonDeger =
| string
| number
| boolean
| null
| JsonDeger[]
| { [anahtar: string]: JsonDeger };
Explanation: Elements of a JSON array are again of type JsonDeger; this allows arrays or objects inside arrays.
3 Recursive types summary
| Term | Meaning |
|---|---|
JsonDeger[] |
Array element is itself |
{ [k: string]: JsonDeger } |
Object values are itself |
string | number |
Primitive options |
DerinPartial |
Nested optional |