Implementing the Observer Design Pattern in TypeScript
A design pattern is a template that solves a commonly recurring problem in software design.
Sign up forfree
Forgot your password?
Create an account
*Required: 8 chars, 1 capital letter, 1 number
By continuing, you agree to thePrivacy PolicyandTerms of Use.You also agree to receive our newsletters, you’re able to opt-out any time.

Here you will learn how to implement the observer design pattern in TypeScript.
The Observer Pattern
The observer pattern works by defining a one-to-many relationship between the publisher and its subscribers. When an event occurs in the publisher, it will notify all subscribers to that event. One widespread example of this pattern isJavaScript event listeners.
For context, assume you’re building an inventory tracker that keeps track of the number of products in your store. In this case, your store is the subject/publisher, and your inventory is the observer/subscriber. Using the observer design pattern would be optimal in this situation.

In the observer design pattern, your subject class must implement three methods:
Your observer class must implement one method, theupdatemethod. This method reacts when there’s a change in its subject’s state.

Implementing the Subject and Observer Classes
The first step to implementing this pattern is to create interfaces for the subject and observer class, to ensure that they implement the correct methods:
The interfaces in the code block above define the methods your concrete classes must implement.

A Concrete Subject Class
The next step is to implement a concrete subject class that implements theSubjectinterface:
Next, initialize theSubject’s state in theStoreclass. The subject’s observers will react to changes to this state.
![]()
In this case, the state is a number, and the observers will react to an increase in the number:
Next, initialize an array of observers. This array is how you’ll keep track of the observers:
You might find some implementations of the observer pattern usinga Set data structurein place of an array to keep track of the observer. Using a Set will ensure that the same observer won’t appear twice. If you want to use an array instead, you should check for duplicate observers in yourattachmethod.
Next, you should implement theSubject’s methods—attach,detach, andnotify/update—in your concrete class.
To implement theattachmethod, first check if the observer is already attached and throw an error if it is. Otherwise, add the observer to the array using theJavaScript array method,push:
Next, implement yourdetachmethod by finding the index and removing it from the array using the JavaScriptsplicemethod.
There can be scenarios where the observer you are trying to detach has already been detached or was not subscribed in the first place. You should handle these scenarios by adding a conditional statement to check if the observer is in the array or the set as the case may be.
Next, implement yournotify/updatemethod by looping over your list of observers and calling theupdatemethod of each one:
Finally, for theSubjectclass, implement a method that manipulates the state and then notifies the observers of the change by calling theirnotify/updatemethod. This example is a simplification of how a subject might perform an action and then inform observers:
Concrete Observer Classes
Create an observer class or classes, to subscribe to the publisher. Each observer class must implement theObserverinterface.
The observer classes will implement anotify/updatemethod which only the subject they are observing should call. This method should contain all the business logic you need to run in response to a change in the subject’s state:
Using the Observer Pattern
To use this pattern, instantiate the concrete subject and observer classes. Once you’ve done so, call the Subject’sattachmethod and pass the Observer instance as an argument. In response, the subject will add that instance to its list of observers:
This code simulates a state change. The change will trigger the notify method on theSubjectclass. This method, in turn, calls thenotifymethod on each of its observers. Each observer will then run its own business logic.
You should only use this pattern when the changes to the state of one object affect other objects, and the set of objects involved is unknown or dynamic.
Advantages of Using the Observer Pattern
Using this pattern in your code allows you to maintain the open/close principle. it’s possible to add as many subscribers as you want, and establish relationships between objects at runtime, without changing the subject’s code.
Many Node.js projects use TypeScript for its strict typing and object-oriented features. Learn how to get started right away.
Quality apps that don’t cost anything.
Obsidian finally feels complete.
Revolutionize your driving experience with these game-changing CarPlay additions.
Lose your laptop without this feature, and you’ll wish you had turned it on.
OneDrive is one of the best, but it has a catch.