Learn
← Previous Next →

Hari 26: Recursive Types

55 min Last updated 09 Apr 2026

Recursive Types di TypeScript

// JSON type (self-referential)
type JSONValue =
    | string | number | boolean | null
    | JSONValue[]
    | { [key: string]: JSONValue };

// Tree node
type TreeNode = {
    value: T;
    children: TreeNode[];
};

// Linked list
type LinkedList = {
    head: T;
    tail: LinkedList | null;
};

// Deep partial
type DeepPartial = {
    [K in keyof T]?: T[K] extends object ? DeepPartial : T[K];
};

💡 Notice: Recursive types dan recursive functions berjalan bersama dengan baik. Sum = 1+2+3+4+5+6 = 21. Depth = 2 level (root → children → grandchildren).

Assignment

Buat fungsi treeSum(node: TreeNode<number>): number yang menjumlahkan semua nilai dalam tree. Buat tree dan test.

Expected output:

Sum: 21
Depth: 2
TS index.ts
Solution
Output