CodeBlanks Logo Icon CodeBlanks

What is a recursive type?

Learn self-referencing types.

What is a recursive type?

A recursive type is a type that references itself in its definition. Linked lists, trees, and nested structures are defined this way. A field points to a value of the same type; this allows modeling data of unlimited depth. The chain can be terminated by making the field optional (?).

type LinkedList<T> = {
  value: T;
  next?: LinkedList<T>;
};

Termination with optional fields

In recursive types, the self-referencing field is made optional (?); this lets the chain end at some point. For example, in next?: LinkedList<T>, if next is absent the list ends. This allows modeling finite data without falling into infinite recursion.

Practice Create a linked list object

Define a recursive generic type named BagliListe: <T> = { deger: T; sonraki?: BagliListe<T> }. The liste variable should be of type BagliListe<number> with value { deger: 1, sonraki: { deger: 2 } }. Print liste.deger with console.log.

Starter code

index.ts
// BagliListe adinda recursive generic type tanimla
// deger ve opsiyonel sonraki alanlari olsun
// liste nesnesini number degerlerle tanimla
// liste.deger yazdir

Sample solution

index.ts
type BagliListe<T> = {
  deger: T;
  sonraki?: BagliListe<T>;
};
const liste: BagliListe<number> = { deger: 1, sonraki: { deger: 2 } };
console.log(liste.deger);

Expected output

1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the defining feature of a recursive type?

  • It contains only primitive types
  • It changes at runtime
  • It cannot take generic parameters
  • It references itself in its definition Correct answer

Explanation: A recursive type references its own name in its definition; this allows modeling nested data of unlimited depth.

2 Self-reference

Question
type BagliListe<T> = {
  deger: T;
  sonraki?: ____<T>;
};
Answer
type BagliListe<T> = {
  deger: T;
  sonraki?: BagliListe<T>;
};

Explanation: A recursive type references itself; the next field must also be of type BagliListe<T>.

3 Recursive type concepts

Term Meaning
deger Node value
sonraki? Optional next node
BagliListe<T> Self-referencing type
T Type of node value

All lessons in Advanced