javascript / expert
Snippet
Enforcing Read-Only Signal Views with Angular's asReadonly()
In large Angular applications, exposing a raw WritableSignal from a service lets any component call .set() or .update() on it, bypassing the store's intended mutation methods and making state changes untraceable. asReadonly() returns a signal that shares the same underlying value and change notifications as the original, but strips the .set/.update API at the type level, so TypeScript rejects direct mutation attempts at compile time. This is a zero-cost wrapper — no extra subscription or memory overhead — making it the idiomatic way to enforce encapsulation in signal-based services without resorting to RxJS Subjects with asObservable().
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { Injectable, signal, computed } from '@angular/core';interface CartItem {sku: string;qty: number;}@Injectable({ providedIn: 'root' })export class CartStore {private readonly _items = signal<CartItem[]>([]);// Public consumers get a WritableSignal-shaped read-only view.readonly items = this._items.asReadonly();readonly total = computed(() =>this._items().reduce((sum, i) => sum + i.qty, 0));addItem(item: CartItem): void {this._items.update((list) => [...list, item]);}removeSku(sku: string): void {this._items.update((list) => list.filter((i) => i.sku !== sku));}}
angular
Breakdown
1
private readonly _items = signal<CartItem[]>([]);
The private, mutable source of truth — only this class can call .set() or .update() on it.
2
readonly items = this._items.asReadonly();
Exposes a read-only signal reference; consumers can read and react to it but cannot mutate it directly.
3
readonly total = computed(() => ...)
Derived state recomputes automatically whenever _items changes, staying in sync without manual wiring.
4
this._items.update((list) => [...list, item]);
The only sanctioned mutation path, keeping state changes centralized and debuggable.