Creating Self-Referencing Objects in TypeScript
Problem
Let’s consider a quick example: how would you create an object with the Node
interface?
The problem is that you need a Node
object reference for the self
property. And to create the object you need to specify its self
property. And so on, and so on.
Solution
The possible solution for this is to use a Partial
mapped type. Here’s the code snippet for the solution:
Partial<Node>
returns a type that has got the same properties as Node, but those properties are optional. This allows to instanciate the object without specifying the self
property right away. Once the object has been created, we can reference the object for the self
property.
It’s important to cast the object from Partial<Node>
back to Node
before starting using it.