SOLID Principles in JavaScript and TypeScript: Practical Frontend Examples

What is SOLID?
SOLID is a set of five design principles that help you write code that is easier to read, test and change. The name comes from the first letters of each principle:
- Single Responsibility: one module should have one reason to change.
- Open/Closed: add new behavior without editing old code.
- Liskov Substitution: a subtype must work wherever its parent type is expected.
- Interface Segregation: do not force code to depend on things it does not use.
- Dependency Inversion: depend on abstractions, not on concrete details.
The principles were collected by Robert C. Martin for object-oriented languages, but they are useful in JavaScript and TypeScript too, with classes and also with plain functions, React components and hooks, and Angular services. In this post I show each principle with a short "bad" and "better" example from frontend code.
Keep in mind that SOLID is a set of guidelines, not strict laws. The goal is simpler code, not more code.
In the examples I use a simple Player type with an id, a nickname and a level.
S: Single Responsibility Principle
A function, class or component should have one reason to change. If one piece of code does several jobs, a change in one job can break the others.
This function loads players, formats them and renders them to the page. It has three reasons to change: the API changes, the text format changes, or the HTML changes.
async function showPlayers() {
const response = await fetch('/api/players');
const players: Player[] = await response.json();
const list = document.querySelector('#players')!;
list.innerHTML = '';
for (const player of players) {
const item = document.createElement('li');
item.textContent = `${player.nickname.toUpperCase()} (level ${player.level})`;
list.append(item);
}
}
Better: split it so every function does one thing.
async function fetchPlayers(): Promise<Player[]> {
const response = await fetch('/api/players');
return response.json();
}
function formatPlayer(player: Player): string {
return `${player.nickname.toUpperCase()} (level ${player.level})`;
}
function renderList(list: HTMLElement, items: string[]): void {
list.replaceChildren(
...items.map((text) => {
const item = document.createElement('li');
item.textContent = text;
return item;
}),
);
}
async function showPlayers() {
const players = await fetchPlayers();
const list = document.querySelector<HTMLElement>('#players')!;
renderList(list, players.map(formatPlayer));
}
Now you can test formatPlayer without a browser, change the API without touching the HTML, and reuse renderList for other lists.
In React, the same idea means keeping data loading out of the component. The component only describes what to show, and a custom hook takes care of the data:
function PlayerList() {
const players = usePlayers(); // fetching and state live in the hook
return (
<ul>
{players.map((player) => (
<PlayerItem key={player.id} player={player} />
))}
</ul>
);
}
A warning sign for this principle: a component with many useState, useEffect and API calls, which also has a lot of markup.
O: Open/Closed Principle
Code should be open for extension, but closed for modification. When you need a new behavior, you should add new code, not edit the old, working code.
A typical bad example is a form validator with a growing if chain:
function validate(value: string, type: 'required' | 'email' | 'minLength'): string | null {
if (type === 'required') {
return value ? null : 'This field is required';
}
if (type === 'email') {
return value.includes('@') ? null : 'Enter a valid email';
}
if (type === 'minLength') {
return value.length >= 3 ? null : 'Enter at least 3 characters';
}
return null;
}
Every new rule (maxLength, phone...) means editing this function, and every edit can break the old rules.
Better: each rule is a small function with the same shape, and validate only runs them:
type Validator = (value: string) => string | null;
const required: Validator = (value) =>
value ? null : 'This field is required';
const email: Validator = (value) =>
value.includes('@') ? null : 'Enter a valid email';
const minLength = (min: number): Validator => (value) =>
value.length >= min ? null : `Enter at least ${min} characters`;
function validate(value: string, validators: Validator[]): string[] {
return validators
.map((validator) => validator(value))
.filter((error): error is string => error !== null);
}
console.log(validate('ab', [required, minLength(3)]));
// Output: ['Enter at least 3 characters']
A new rule is a new function. validate never changes. The same pattern works for many frontend problems: button variants, table column renderers, route guards, or a list of middleware functions.
A warning sign for this principle: a switch or if / else if chain on a "type" that grows every time a feature is added.
L: Liskov Substitution Principle
The Liskov Substitution Principle states that an object of a subclass should be able to replace an object of its superclass without breaking the code. In other words, if your code works with a type A, it should also work with any subtype of A, without surprises. A child class must keep the promises of its parent.
Imagine a simple store for settings, and a function that uses it:
interface Store {
get(key: string): string | null;
set(key: string, value: string): void;
}
class LocalStore implements Store {
get(key: string) {
return localStorage.getItem(key);
}
set(key: string, value: string) {
localStorage.setItem(key, value);
}
}
function saveTheme(store: Store) {
store.set('theme', 'dark');
}
Now somebody needs a read-only store and creates a subclass that blocks saving:
class ReadOnlyStore extends LocalStore {
set(): void {
throw new Error('This store is read only');
}
}
saveTheme(new ReadOnlyStore());
// Output: Error: This store is read only
TypeScript is happy, because the types match. But saveTheme was written for a Store, and a ReadOnlyStore breaks it at runtime. The subclass cannot be substituted for its parent, so it violates the principle.
Better: do not pretend that a read-only store can save. Describe the difference in the types:
interface ReadableStore {
get(key: string): string | null;
}
interface WritableStore extends ReadableStore {
set(key: string, value: string): void;
}
class ReadOnlyStore implements ReadableStore {
get(key: string) {
return localStorage.getItem(key);
}
}
function saveTheme(store: WritableStore) {
store.set('theme', 'dark');
}
saveTheme(new ReadOnlyStore());
// Error: Property 'set' is missing in type 'ReadOnlyStore'
Now the mistake is found by the compiler, not by your users.
The frontend version of this problem is very common with UI components: a DisabledButton that extends Button but ignores clicks, or a ReadOnlyInput that throws when setValue is called. Warning signs are overridden methods that throw an error, do nothing, or have a different meaning than the parent method. Often composition (a component that uses another component) is a safer choice than inheritance.
I: Interface Segregation Principle
Code should not be forced to depend on things it does not use. It is better to have a few small, focused interfaces than one big one.
In frontend code you meet this problem most often in component props. Here a small card needs only a name and an avatar, but it asks for the whole User object:
type User = {
id: number;
name: string;
email: string;
avatarUrl: string;
address: { city: string; street: string };
roles: string[];
// ...and many more fields
};
function UserCard({ user }: { user: User }) {
return (
<div>
<img src={user.avatarUrl} alt={user.name} />
<h3>{user.name}</h3>
</div>
);
}
The card now depends on every field of User. To show it in a test or in Storybook you must build a full user with an address and roles. And when User changes, the card may be affected, although it uses only two fields.
Better: ask only for what you need.
type UserCardProps = Pick<User, 'name' | 'avatarUrl'>;
function UserCard({ name, avatarUrl }: UserCardProps) {
return (
<div>
<img src={avatarUrl} alt={name} />
<h3>{name}</h3>
</div>
);
}
<UserCard name="Neo" avatarUrl="/neo.png" />
The same applies to service interfaces. If one big interface has many methods, every class that implements it must handle all of them, even when it needs only one:
// Too big
interface PlayerApi {
getAll(): Promise<Player[]>;
getById(id: number): Promise<Player>;
create(player: NewPlayer): Promise<Player>;
update(player: Player): Promise<Player>;
remove(id: number): Promise<void>;
}
// Better: small interfaces that can be combined
interface PlayerReader {
getAll(): Promise<Player[]>;
getById(id: number): Promise<Player>;
}
interface PlayerWriter {
create(player: NewPlayer): Promise<Player>;
update(player: Player): Promise<Player>;
remove(id: number): Promise<void>;
}
A read-only page depends only on PlayerReader, so it does not care when the writing methods change.
A warning sign for this principle: props with a huge object, tests that need a lot of fake data just to render a small component, or classes with empty methods that exist only because an interface demanded them.
D: Dependency Inversion Principle
High-level code (your business logic) should not depend on low-level details (fetch, localStorage, a specific library). Both should depend on an abstraction, such as an interface.
Here the service calls fetch directly:
class PlayerService {
async getTopPlayers(): Promise<Player[]> {
const response = await fetch('/api/players');
const players: Player[] = await response.json();
return players.sort((a, b) => b.level - a.level).slice(0, 3);
}
}
The logic ("top three by level") is stuck together with the network call. To test it you need a real server or a global mock of fetch. If you switch to another HTTP library, you must edit the service.
Better: the service asks for something that can load players, and does not care how it does it.
interface PlayerApi {
getAll(): Promise<Player[]>;
}
class PlayerService {
constructor(private api: PlayerApi) {}
async getTopPlayers(): Promise<Player[]> {
const players = await this.api.getAll();
return [...players].sort((a, b) => b.level - a.level).slice(0, 3);
}
}
// Real implementation, used in the app
class HttpPlayerApi implements PlayerApi {
async getAll(): Promise<Player[]> {
const response = await fetch('/api/players');
return response.json();
}
}
const service = new PlayerService(new HttpPlayerApi());
Now a test is very simple, because you can give the service a fake:
const fakeApi: PlayerApi = {
getAll: async () => [
{ id: 1, nickname: 'Neo', level: 5 },
{ id: 2, nickname: 'Trinity', level: 9 },
{ id: 3, nickname: 'Morpheus', level: 7 },
{ id: 4, nickname: 'Cypher', level: 1 },
],
};
const top = await new PlayerService(fakeApi).getTopPlayers();
console.log(top.map((player) => player.nickname));
// Output: ['Trinity', 'Morpheus', 'Neo']
The direction of the dependency is "inverted": the service no longer depends on fetch, and the HTTP code depends on the interface that the service defines.
This is the idea behind dependency injection. You may already use it without the name: Angular injects services through its constructor, and in React you can pass dependencies as props or share them with context. The point is not to use a special framework feature, but to receive your dependencies from the outside instead of creating them inside.
A warning sign for this principle: business logic that imports fetch, axios, localStorage or window directly, and tests that need many global mocks.
Cheat sheet
| Principle | In one sentence | Warning sign in frontend code | Typical fix |
|---|---|---|---|
| Single Responsibility | One reason to change | A component that fetches, formats and renders | Split into hook or service, formatter and component |
| Open/Closed | Extend without editing old code | A switch or if chain that grows with every feature |
A map or list of small functions |
| Liskov Substitution | A subtype works wherever the parent works | An override that throws or does nothing | Smaller interfaces, or composition instead of inheritance |
| Interface Segregation | Depend only on what you use | Props that take a huge object for two fields | Pick the needed fields, split big interfaces |
| Dependency Inversion | Depend on abstractions, not details | Business logic that calls fetch or localStorage directly |
Pass the dependency in through an interface |
Do not overdo it
SOLID can be misused. A beginner who has just learned it may create an interface for every function, a class for every small task, and five files for a button. That makes code harder to read, not easier.
A few rules that help:
- Wait for the pain. Do not add an abstraction for a second implementation that does not exist yet. When you really need it, it is usually easy to extract.
- Prefer simple code. A short function that is easy to read is better than a "perfect" structure that nobody understands.
- Use the principles as questions, not as rules: "Why does this change?", "Will I have to edit this again for the next feature?", "Can I test this without a server?"
If a principle does not make your code simpler or easier to test, you probably do not need it in that place.
Summary
SOLID helps you keep frontend code easy to change and test. Give each function or component one job (S), extend behavior by adding code instead of editing it (O), make sure subtypes do not break their parents (L), ask components and services only for what they use (I), and let your logic depend on interfaces instead of fetch or localStorage (D). Apply the principles when you feel the pain, and keep the code as simple as the problem allows.
About the author
Front-end developer who pays special attention to the aesthetics and functionality of websites. I love playing with interesting design solutions, creating interfaces that not only work efficiently, but also attract attention with their unique design. I like to derive pleasure from it, like with my old 'Portfolio' website. After hours, I return to classic games or good movies that stimulate the imagination.
Comments
Join the discussionNo comments yet. Be the first to comment.





