Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

TypeScript Recursive Types

TypeScript Recursive Types

A recursive type is a type that refers to itself; it is very useful when working with tree structures and nested data.

TypeScript supports recursive type definitions and can express data structures of unlimited depth.


How recursive types work Base node interface TreeNode { value: string } Recursive reference Recursive type interface TreeNode { value: string children?: TreeNode[] } Actual structure root ├── child1 └── child2 Applications of recursive types Tree structure Nested objects Deep type conversion

Why recursive types are needed

In the real world, data structures are often nested.

For example, a file system has folders and subfolders, an organization has departments and sub-departments, and JSON data can be nested indefinitely.

Recursive types allow us to express such infinitely nested structures and are the foundation for working with tree data.

Concept:A recursive type is a type that refers to itself in its definition and can express nested structures of any depth.


Tree structure

The most common application of recursive types is representing tree structures.

Example

// Define the tree node type; children refers to itself

interface

TreeNode

{

    id

:

number

;

                   

// Node ID

    name

:

string

;

                 

// Node name

    children

?:

TreeNode

[

]

;

       

// Array of child nodes, recursively referencing

}

// Create a tree structure

const

fileSystem

:

TreeNode

=

{

    id

:

1

,

    name

:

"Root directory"

,

    children

:

[

       

{

            id

:

2

,

            name

:

"Folder1"

,

            children

:

[

               

{

id

:

5

,

name

:

"FileA.txt"

}

,

               

{

id

:

6

,

name

:

"FileB.txt"

}

           

]

       

}

,

       

{

            id

:

3

,

            name

:

"Folder2"

,

            children

:

[

               

{

id

:

7

,

name

:

"FileC.txt"

}

           

]

       

}

,

       

{

            id

:

4

,

            name

:

"File.txt"

       

}

   

]

}

;

// Function to traverse the tree

function

traverse

(

node

:

TreeNode

,

depth

:

number

=

0

)

:

void

{

   

const

indent

=

"  "

.

repeat

(

depth

)

;

    console.

log

(

indent

"📁 "

node.

name

)

;

   

if

(

node.

children

)

{

       

for

(

const

child of node.

children

)

{

            traverse

(

child

,

depth

1

)

;

       

}

   

}

}

traverse

(

fileSystem

)

;

Running result:

📁 根目录

  📁 文件夹1

    📁 文件A.txt

    📁 文件B.txt

  📁 文件夹2

    📁 文件C.txt

  📁 文件.txt

File system:Tree structures are a classic application of recursive types and can represent directory trees, organizational structures, etc.


Nested lists

Recursive types can also represent nested list structures.

Example

// Define the nested list type

type NestedList

<

T

=

T

|

NestedList

<

T

[

]

;

// Define the task type

interface

Task

{

    id

:

number

;

    title

:

string

;

    completed

:

boolean

;

}

// Create a nested task list

const

tasks

:

NestedList

<

Task

=

[

{

id

:

1

,

title

:

"ProjectA"

,

completed

:

false

}

,

   

[

       

{

id

:

2

,

title

:

"Subtask1"

,

completed

:

true

}

,

       

{

id

:

3

,

title

:

"Subtask2"

,

completed

:

false

}

   

]

,

   

{

id

:

4

,

title

:

"ProjectB"

,

completed

:

false

}

]

;

// Calculate the depth of the nested list

function

getDepth

<

T

(

list

:

NestedList

<

T

,

depth

:

number

=

0

)

:

number

{

   

if

(

Array

.

isArray

(

list

)

)

{

        let maxDepth

=

depth

1

;

       

for

(

const

item of list

)

{

            maxDepth

=

Math

.

max

(

maxDepth

,

getDepth

(

item

,

depth

1

)

)

;

       

}

       

return

maxDepth

;

   

}

   

return

depth

;

}

console.

log

(

"List depth: "

getDepth

(

tasks

)

)

;

Union type:Using T | NestedList[] can handle both a single element and an array.


Deep readonly types

Use recursive types to achieve deep readonly conversion.

Example

// Deep readonly type - applied recursively

type DeepReadonly

<

T

=

T

extends

Function

?

T

// Functions remain as they are

   

:

T

extends

object

       

?

{

readonly

[

P

in

keyof T

]

:

DeepReadonly

<

T

[

P

]

}

:

T

;

// User type

interface

User

{

    name

:

string

;

    profile

:

{

        email

:

string

;

        address

:

{

            city

:

string

;

            zip

:

string

;

       

}

;

   

}

;

    friends

:

User

[

]

;

}

// Create a deeply readonly user

const

user

:

DeepReadonly

<

User

=

{

name

:

"Alice"

,

    profile

:

{

        email

:

"alice@test.com"

,

        address

:

{

            city

:

"Beijing"

,

            zip

:

"100000"

       

}

   

}

,

    friends

:

[

]

}

;

// Trying to modify will cause an error

// user.name = "Bob"; // Error: name is readonly

// user.profile.address.city = "Shanghai"; // Error: deep properties are readonly too

console.

log

(

"User: "

user.

name

)

;

console.

log

(

"City: "

user.

profile

.

address

.

city

)

;

Recursive conversion:DeepReadonly recursively converts all nested object properties to readonly.


Deep optional types

Use recursive types to achieve deep optional conversion.

Example

// Deep optional type - applied recursively

type DeepPartial

<

T

=

T

extends

object

?

{

[

P

in

keyof T

]

?:

DeepPartial

<

T

[

P

]

}

:

T

;

// Configuration type

interface

AppConfig

{

    database

:

{

        host

:

string

;

        port

:

number

;

        credentials

:

{

            username

:

string

;

            password

:

string

;

       

}

;

   

}

;

    server

:

{

        port

:

number

;

        ssl

:

boolean

;

   

}

;

}

// With deep optional, you can provide only part of the configuration

const

partialConfig

:

DeepPartial

<

AppConfig

=

{

database

:

{

        host

:

"localhost"

       

// port and credentials are optional

   

}

   

// server is optional

}

;

console.

log

(

"Database host: "

partialConfig.

database

?

.

host

)

;

Optional nesting:DeepPartial recursively makes all properties optional, making it easy to handle partial configurations.


Chained data structures

Recursive types can represent chained data structures such as linked lists.

Example

// Linked list node type

interface

ListNode

<

T

{

value

:

T

;

             

// The value of the current node

    next

?:

ListNode

<

T

;

   

// The next node, recursively referenced

}

// Create a linked list

const

linkedList

:

ListNode

<

number

=

{

value

:

1

,

    next

:

{

        value

:

2

,

        next

:

{

            value

:

3

,

            next

:

{

                value

:

4

,

                next

:

undefined

           

}

       

}

   

}

}

;

// Traverse the linked list

function

traverseList

<

T

(

node

:

ListNode

<

T

)

:

void

{

    let current

:

ListNode

<

T

|

undefined

=

node

;

   

const

values

:

T

[

]

=

[

]

;

    while

(

current

)

{

        values.

push

(

current.

value

)

;

        current

=

current.

next

;

   

}

    console.

log

(

"Linked list values: "

values.

join

(

" -> "

)

)

;

}

traverseList

(

linkedList

)

;

// Calculate the length of the linked list

function

getLength

<

T

(

node

:

ListNode

<

T

)

:

number

{

    let length

=

0

;

    let current

:

ListNode

<

T

|

undefined

=

node

;

    while

(

current

)

{

        length

++;

        current

=

current.

next

;

   

}

   

return

length

;

}

console.

log

(

"Linked list length: "

getLength

(

linkedList

)

)

;

Linked list:ListNode By referencing itself through next, it forms a chained structure, a classic application of recursive types.


Recursion in union types

Use recursive types to handle union types in JSON data.

JSON types:Recursive types can precisely express all possible types of JSON.

Example

// Recursive type definition for JSON values

type JSONValue

=

string

|

number

|

boolean

|

null

|

JSONValue

[

]

|

{

[

key

:

string

]

:

JSONValue

}

;

// Define a configuration object

const

config

:

JSONValue

=

{

   

"name"

:

"my-app"

,

   

"version"

:

"1.0.0"

,

   

"enabled"

:

true

,

   

"settings"

:

{

       

"debug"

:

false

,

       

"ports"

:

[

3000

,

8080

]

,

       

"metadata"

:

{

           

"author"

:

"Alice"

,

           

"tags"

:

[

"web"

,

"typescript"

]

       

}

   

}

}

;

// Function to get a JSON value

function

getValue

(

obj

:

JSONValue

,

path

:

string

)

:

JSONValue

|

undefined

{

   

const

keys

=

path.

split

(

"."

)

;

    let current

:

JSONValue

|

undefined

=

obj

;

   

for

(

const

key of keys

)

{

       

if

(

current

&&

typeof

current

===

"object"

&&

!

Array

.

isArray

(

current

)

)

{

            current

=

(

current as

{

[

key

:

string

]

:

JSONValue

}

)

[

key

]

;

       

}

else

{

           

return

undefined

;

       

}

   

}

   

return

current

;

}

console.

log

(

"Version: "

getValue

(

config

,

"version"

)

)

;

console.

log

(

"Port: "

getValue

(

config

,

"settings.ports"

)

)

;

console.

log

(

"Author: "

getValue

(

config

,

"settings.metadata.author"

)

)

;


Notes

Best practices:Recursive types are a powerful tool for working with tree and nested data; mastering them can solve many complex type problems.


Summary

Recursive types are an advanced feature of the TypeScript type system.

Note:When working with nested data, prefer recursive types to ensure type safety.